Arrays with fields_for ?

0 views
Skip to first unread message

Rick Schumeyer

unread,
Feb 15, 2007, 12:42:26 AM2/15/07
to rubyonra...@googlegroups.com
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.

Rick

unread,
Feb 15, 2007, 9:11:52 AM2/15/07
to Ruby on Rails: Talk
Sorry for the bump, but I'm still hoping someone can help.

Reply all
Reply to author
Forward
0 new messages