I read the section from AWDWR 2ed beginning at p. 337 about using a
model to join tables. I’m trying to combine this concept with having
multiple models on one form.
Let’s say I have classes Account and Employee, with a many-to-many
relationship between them. I don’t want to use a pure join table
because I want the AccountEmployee table to also contain a column for
“role”. (Actually, I will name the join table AccountEmployeeRelations)
I believe the model would look like this:
class Account < AR::Base
has_many :account_employee_relations
has_many :employees :through => :account_employee_relations
end
class Employee < AR::Base
has_many :account_employee_relations
has_many :accounts :through => :account_employee_relations
end
I assume I also need (but the book does not show):
class AccountEmployeeRelation < AR::Base
belongs_to :accounts
belongs_to :employees
end
In the migration for AccountEmployeeRelation I would guess I need lines
like:
t.column :account_id, :integer
t.column :employee_id, :integer
t.column :role, :string
The rest of my question probably depends on my interface. I guess I
could first create an account, and then on a separate form assign
employees to that account. I haven’t tried that, but I would expect
that approach to be fairly easy.
But if I want to create the account and assign the employees in one
form, I turn to p. 490 “Multiple Models in a Form”. Let’s look at the
controller and view for edit/update (I might be able to figure out the
rest once I have this part).
def edit
@account = account.find(params[:id])
@account_employee_relations = @account.employee_account_relations #
I think this is an array ?
end
I haven’t worked on update yet since I can’t get edit to work…but
I’m sure this won’t work.
def update
@account = account.find(params[:id])
if @account.update_attributes(params[:account])
flash[:notice] = ‘account was successfully updated.’
redirect_to :action => ‘show’, :id => @account
else
render :action => ‘edit’
end
end
I’m quite lost on this section of edit.rhtml:
<% form_for :account, @account, :url => { :action => “update”, :id =>
@account } do |form| %>
…
<% @account_employee_relations.each do |r| %>
<% fields_for r do |f| %>
Any help is appreciated!