umezo
umezo

Reputation: 1579

Updating models in has_many :through association

I have two models, Designer and Influence. They have a "has_many" relationship to eachother :through a join model called Relation.

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.

Designer.rb

attr_accessible :name, :relation, :influence
has_many :relations
has_many :influences, :through => relations

Influence.rb

attr_accessible :name, :relation, :designer
has_many :relations
has_many :designers, :through => :relations

Relation.rb

attr_accessible :designer_id, :influence_id
belongs_to :designer
belongs_to :influence

designers/_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

def update
  @designer = current_designer
  ** Is there a way to create a new relation object here? **

Upvotes: 0

Views: 752

Answers (1)

jordanpg
jordanpg

Reputation: 6516

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:

Relation.create relation_attributes

or

@designer.influences.create influence_attributes (this creates a new Relation object)

Upvotes: 1

Related Questions