Skip to content

Instantly share code, notes, and snippets.

@dohoonk
Last active March 19, 2016 23:42
Show Gist options
  • Save dohoonk/20e252cbbd21809ef7d6 to your computer and use it in GitHub Desktop.
Save dohoonk/20e252cbbd21809ef7d6 to your computer and use it in GitHub Desktop.
Handling background job with Redis and Sidekiq/Polymorphic associations

##Delayed Job/Backgorund Job

1 brew install redis

2 To start the server redis-server

3 gem install redis

4 redis desktop manager

5 In your redis desktop manager connet to redis server name: localhost Host: localhost

6 Add gem sidekiq

gem 'sidekiq'

run bundle

7 In your config -> application.rb add this line of code

config.autoload_paths << Rails.root.join("app","jobs")
config.autoload_paths << Rails.root.join("app","uploaders")
config.active_job.queue_adapter = :sidekiq

8 We can setup a delayed jobs that will happen at specific time

bin/rails g job determine_campaign_state
def perform(*args)
  campaign = args[0]
  campaign.fund!
end

sidekiq requires sinatra gem 'sinatra'

Polymorphic association

If a model has many associations assigning them to a single model will leave many empty fields To address this problem we can use polymorphic association

Ex. commentable_type commentable_id

bin/rails g model comment body:text commentable:references{polymorphic}

bin/rake db:migrate

In the campaign model has_many :comments, as: :commentable

We need to setup the controller bin/rails g controller comments

In your routes resources :comments, only: [:create]

Comments.controller

before_action :authenticate_user
before_action :find_commentable

def create
  @comment = Comment.new comment_params
  @comement.commentalbe = @commentable
  if @comment.save
    redirect_to @commentable, notice: "Comment created"
  else
    folder_name = @commentable.class.to_s.underscore.pluralize
    render "/#{folder_name}/show"
  end
end

private

def comment_params
  commet_params(:comment).permit(:body)
end

def find_commentable
  if params[:campaign_id]
    @campaign = @commetable = Campaign.friendly.find params[:campaign_id]
  elsif params[:discussion_id]
    @discussion = @commetable = Discussion.friendly.find params[:discussion_id]
  end
end
<%= simple_form_for [@campaign,@comment] do |f| %>

<%end%>

add validation to comment

validates :body, presence: true

display list of comments

<%= @campaign.comments.each do |com|%>
<div class="well">
  <%=com.body%>
</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment