[英]Updating models in has_many :through association
I have two models, Designer and Influence. 我有两个模型,Designer和Impact。 They have a "has_many" relationship to eachother :through a join model called Relation. 他们彼此之间有一个“ has_many”关系:通过一个称为“关系”的联接模型。
I want to use a single form to create/update the designer model with information from the influence model. 我想使用一种形式来使用影响模型中的信息来创建/更新设计器模型。 Is it possible to create a relation object through the create/update actions in the designer controller? 是否可以通过设计器控制器中的创建/更新操作来创建关系对象? Or do I need to create a Relations controller? 还是我需要创建一个关系控制器?
My current code is as below, and results in a NoMethodError in DesignersController#Update. 我当前的代码如下,并在DesignersController#Update中导致NoMethodError。
Designer.rb Designer.rb
attr_accessible :name, :relation, :influence
has_many :relations
has_many :influences, :through => relations
Influence.rb Impact.rb
attr_accessible :name, :relation, :designer
has_many :relations
has_many :designers, :through => :relations
Relation.rb 关系.rb
attr_accessible :designer_id, :influence_id
belongs_to :designer
belongs_to :influence
designers/_form.html.erb designer / _form.html.erb
<%= form_for @designer do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.label :influence %><br />
<%= f.collection_select :influence, Influence.order(:name), :id, :name, include_blank: true %>
<%= f.submit %>
<% end %>
designers_controller.rb designer_controller.rb
def update
@designer = current_designer
** Is there a way to create a new relation object here? **
There are 2 general ways to do this. 有两种一般的方法可以做到这一点。 You can create a Relations object directly or you can create an Influence object using the Designer association, and one will be made automatically: 您可以直接创建一个Relations对象,也可以使用Designer关联创建一个Impact对象,然后将自动创建一个对象:
Relation.create relation_attributes
or 要么
@designer.influences.create influence_attributes
(this creates a new Relation object) @designer.influences.create influence_attributes
(这将创建一个新的Relation对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.