Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2polymorphic-associations

How to pass user id and type in table from controller for polymorphic assosiation in Ruby on Rails


I have been struggling all day to pass a user ID and type into tagging table when I create my new tagging

In the Tagging Controller i have this code:

def create
    @taggable = Blog.find(params[:blog_id])
    @tagger = current_user
    @tagging = @taggable.taggings.build(params[:taggings])
    respond_to do |format|
      if @tagging.save!
        format.js {render status: :created}       
      end
    end
  end

In this Tagging Model i have this code

 belongs_to :taggable, :polymorphic => true
 belongs_to :tagger, :polymorphic => true

In this Blog Model i have this code

attr_accessible :description,:user_id,:title,:taggings_attributes,:tagger_attributes
 has_many :taggings, as: :taggable
 has_many :tagger, as: :taggable,:class_name=>"Tagging"

Now I want something like this

@tagging = @[email protected](params[:taggings])

Solution

  • You can assign the user anytime after you build the new Tag object and before you save it.

    For example,

    @tagging = @taggable.taggings.build(params[:taggings])
    @tagging.tagger_id = @tagger.user.id
    @tagging.tagger_type = 'User'
    

    You can also assign the user directly, rather than the tagger_id and tagger_type.

    @tagging = @taggable.taggings.build(params[:taggings])
    @tagging.tagger = @tagger.user