samedi 18 avril 2015

Rails form helper adding an associated model through collection_select

I have troubles adding an associated model through a collection_select method. Here are my two models



class Signatory < ActiveRecord::Base
belongs_to :bank
end


and



class Bank < ActiveRecord::Base
has_many :signatories
end


I have some banks already added in my "banks" table and I want to add a signatory with the associated bank_id field populated through a drop-down list. Here the code of the form:



<%= form_for(@signatory) do |f| %>
<%= f.label :bank_id %>
<%= f.collection_select(:bank, Bank.all, :id, :name %>

<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%#-... %>
<%= f.submit "Add signatory" %>
<% end %>


These are the relevant parts of my controllers:



def new
@signatory = Signatory.new
end
def create
@signatory = bank.signatories.build(signatory_params)
@signatory.save
end


The console shows the following hash which is what I expect:



Parameters: {... "signatory"=>{"bank_id"=>"1", "first_name"=>"Al", "last_name"=>"Smith", "email"=>"Al@"}, "commit"=>"Add signatory"}


However, I get the error message undefined local variable or method 'bank'. If I add the line



bank = Bank.find(1)


in the create action, it would work, obviously. How/When/where do I define the 'bank' variable? What am I missing in the controller to have the form pass the 'bank_id' attribute to the 'bank' variable and then save it into my signatory table? Thanks.


Aucun commentaire:

Enregistrer un commentaire