Updating :has_many - :through related items


#1

Hi,

I’ve got my little app working pretty well. I’m using pretty much the
model and table layout from my previous thread, as suggested by Bill
Katz:

http://www.ruby-forum.com/topic/52506#26260

I have the Create page working and a delete Match page working, which
along with the appropriate record in the Matches table, removes the
linked items in the competitions table.

Now I’m working on the Update page and am not sure I’m doing it the
best way… not to mention it’s not working and looking at the log,
seems to make a ton of trips to the database. My Edit form includes:

<%= "Red 1" if controller.action_name == 'new' %> <%= options_from_collection_for_select(@teams, "id", "number", @match_teams[0]) %> <%= "Red 2" if controller.action_name == 'new' %> <%= options_from_collection_for_select(@teams, "id", "number", @match_teams[1]) %> <%= "Red 3" if controller.action_name == 'new' %> <%= options_from_collection_for_select(@teams, "id", "number", @match_teams[2]) %>

(There are three more tags for the “blue” side, using
@match_teams[3] through 5)

The Edit controller defines @match_teams as:

@match = Match.find(params[:id])
@teams = Team.find(:all, :order => “number”)
@match_teams = []
@match.competitions.each do |team|
@match_teams << team.team_id
end

Now in the update method I’m doing this, but it looks messy and
doesn’t seem to update the correct records:

@match = Match.find(params[:id])
if @match.update_attributes(params[:match])
for i in 0…2
if @match.competitions[i].team_id != params[:Red][i] then
@match.competitions[i].team_id = params[:Red][i]
@match.competitions[i].save
end
end
for i in 3…5
if @match.competitions[i].team_id != params[:Blue][i] then
@match.competitions[i].team_id = params[:Blue][i]
@match.competitions[i].save
end
end

Is there a better way to do what I want… update all of the
corresponding changed items?

Thanks.

jt


#2

On 1/30/06, John T. removed_email_address@domain.invalid wrote:

Hi,

Well, I figured out why it wasn’t working. In this bit:

if @match.competitions[i].team_id != params[:Blue][i] then
  @match.competitions[i].team_id = params[:Blue][i]
  @match.competitions[i].save
end

end

I had to change the comparison to:
if @match.competitions[i].team_id != params[:Red][i].to_i

to compare integers. And the second loop, I had to change the
params[:Blue][i] to params[:Blue][i-3]

It works now, but I’d still like to know if I’m doing more work than
necessary, or missing some “Ruby-ism” that would help.

Thanks.
jt