rails creating model with multiple belongs_to, with attr_accessible

k_day picture k_day · Jan 20, 2012 · Viewed 8.3k times · Source

My models look something like this:

class User < ActiveRecord::Base
    attr_accessible: :name

    has_many :reviews   
end

class Product < ActiveRecord::Base
    attr_accessible: :name

    has_many :reviews   
end

class Review < ActiveRecord::Base
    attr_accessible: :comment

    belongs_to :user    
    belongs_to :product
    validates :user_id, :presence => true
    validates :product_id, :presence => true
end

I am trying to figure out what the best way is to create a new Review, given that :user_id and :product_id are not attr_accessible. Normally, I would just create the review through the association ( @user.reviews.create ) to set the :user_id automatically, but in this case I am unsure how to also set the product_id.

My understanding is that if I do @user.reviews.create(params), all non attr_accessible params will be ignored.

Answer

Paul Cantrell picture Paul Cantrell · Jan 20, 2012

You can do:

@user.reviews.create(params[:new_review])

...or similar. You can also use nested attributes:

class User < ActiveRecord::Base
  has_many :reviews
  accepts_nested_attributes_for :reviews
  ...

See "Nested Attributes Examples" on http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html.