Rails:模型的新条目,属于另外两个 [英] Rails: New entry to a model that belongs_to two other

查看:92
本文介绍了Rails:模型的新条目,属于另外两个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,一个产品有很多意见,这些意见是由许多客户撰写的.这是具有关联的模型:

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

在参数中,我具有评估邀请ID,这有助于我同时获得product_id和client_id(因此请考虑我两个都有).

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).

该表单仅包含比率(radio_button,从1到5)和注释(text_field).

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

Opinion#create方法如何创建属于两个模型(客户和产品)的新意见?

我尝试直接传递client_id和product_id,但出现MassAssignment错误:

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

以防万一它有用:在我的应用程序的第一个版本中,意见仅属于产品,使用上面的代码(删除opinion.client_id = client_id行)可以很好地工作,这就是为什么我使用product进行构建的原因意见).因此,这只是一种增强.

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.

推荐答案

product.opinions.build params[:opinion]将建立一个已经将product_id设置为product.id的新意见.由于关联belongs_to :product,它知道要执行此操作.但是,它尚不知道它属于哪个客户端,因此您必须手动设置它.但您需要在Opinion中添加attr_accessible:client_id.

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.

这篇关于Rails:模型的新条目,属于另外两个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆