Rails: New entry to a model that belongs_to two other

这一生的挚爱 提交于 2019-12-12 04:09:41

问题


In my app, a Product has_many opinions, which are written by many clients. Here are models with associations:

class Product < ActiveRecord::Base
    attr_accessible :name, :desc, :price

    has_many :opinions
end

class Client < ActiveRecord::Base
    attr_accessible :name, :bio

    has_many :opinions
end

class Opinion < ActiveRecord::Base
    attr_accessible :rate, :comment

    belongs_to :client, :product
end

In parameters, I have the evaluation invitation id, which helps me to get both product_id and client_id (so consider I have both of them).

The form contains only the rate (radio_button, from 1 to 5) and the comment (text_field).

How does the method opinion#create create the new opinion, which belongs to two models: client and product?

I tried to pass directly client_id and product_id, but I get MassAssignment error:

# Remember: I have product_id and client_id
product = Product.find_by_id product_id

opinion = product.opinions.build params[:opinion]
opinion.product_id = product_id
opinion.client_id = client_id

opinion.save

Just in case it can be useful: in the first version of my app, the opinion belongs only to product, which works well using the above code (remove opinion.client_id = client_id line), that's why I used product to build the opinion). So, this is only an enhancement.

Any idea? Thanks in advance.


回答1:


product.opinions.build params[:opinion] will build a new opinion that already has its product_id set to product.id. It knows to do this because of the association belongs_to :product. However, it does not yet know what client it belongs to, so you have to set this manually. But you need to add attr_accessible :client_id to Opinion to do this.



来源:https://stackoverflow.com/questions/12162570/rails-new-entry-to-a-model-that-belongs-to-two-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!