This is a simpler version of a question I asked earlier that was
probably too long. I am trying to combine an array with fields_for, if
this is possible.
I have classes Account and Employee, with a many-to-many relationship.
I define a model class AccountEmployeeRelation to link the two. The
link class also contains an extra field called "role".
I want to create an Account and assign employees in one form. (The
employees already exist). I have figured out how to add one employee
(not sure if this is the best way, but it works):
Controller:
def new
@account = Account.new
@r = AccountEmployeeRelation.new
end
def create
@account = Account.new(params[:account])
@r = AccountEmployeeRelation.new(params[:r])
@account.account_employee_relations << @r
@account.save
@r.save
redirect_to :action => :list
end
View, new.rhtml:
<% form_for :account, :url => { :action => :create } do |form|
%>
Title: <%= form.text_field :title %><br/>
<% fields_for :r do |r|%>
Employee: <%= r.select (:employee_id, Employee.find(:all).map{|u|
[u.name, u.id]}) %><br/>
Role: <%= r.select (:role, [''Boss'',
''King'', ''Queen'']) %>
<% end %>
<%= submit_tag %>
<% end %>
But how do I assign multiple employees in one form? I would guess that
''new'' needs to look like: (up to 3 employees)
def new
@account = Account.new
@rs = []
3.times do
@rs << AccountEmployeeRelation.new
end
end
But the following does not work for the view. I get this error:
|`@#<AccountEmployeeRelation:0xb7628038>'' is not allowed as an
instance
variable name|
<% for r in @rs %>
<% fields_for r do |f| %>
Employee: <%= f.select (:employee_id, Employee.find(:all).map{|u|
[u.name, u.id]}) %><br/>
Role: <%= f.select (:role, [''Boss'',
''King'', ''Queen'']) %>
<% end %>
<% end %>
Any pointers are appreciated.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---