I am just trying to make my form display a blank field for each item that has not yet been created. I’ve done this successfully using the build method for more simple forms but I’m not sure how to do it for this case. Is the strategy I’m using to do this wrong or am I making a simple syntax mistake?
Here’s the basic model setup:
A Comp has many Rounds and many Teams. A Round has many Items. Each Team has only 1 Item per Round
So when the form is loaded, if a team has not already created an item, I want there to be a blank item created for that team so that it shows up in the form and can be edited for that team.
I tried 2 different methods in my controller and neither has worked:
Method 1:
def edit_admin
@comp = Comp.find(params[:comp_id])
@round = @comp.rounds.find(params[:round_id])
team_ids = @round.items.all(:select => :team_id).collect(&:team_id)
@comp.teams.each do |team|
if team_ids.include? team.id == false
new_item = @round.items.new(:team_id => team.id, :round_id => @round.id)
new_item.save
end
end
end
def update_admin
@comp = Comp.find(params[:comp_id])
@round = @comp.rounds.find(params[:round_id])
if @round.update_attributes(params[:round])
redirect_to(edit_comp_path(@comp))
else
render 'edit_admin'
end
end
Method 2:
Essentially the same thing but I defined a method to run before the page loads:
before_filter :build_new_items, :only => :edit_admin
private
def build_new_items
@comp = Comp.find(params[:comp_id])
@round = @comp.rounds.find(params[:round_id])
team_ids = @round.items.all(:select => :team_id).collect(&:team_id)
@comp.teams.each do |team|
if team_ids.include? team.id == false
new_item = @round.items.new(:team_id => team.id, :round_id => @round.id)
new_item.save
end
end
end
The form looks like this (the view is called edit_admin.html.erb):
<%= form_tag update_admin_comp_round_items_path(@comp,@round), :method => :put do %>
<% for item in @round.items.all %>
<%= "Team: " + @comp.teams.find(item.team_id).team_name %> <br />
<%= fields_for 'round[items_attributes][]', item do |f| %>
<%= f.label :item_name %>
<%= f.text_field :item_name %> <br />
<%= f.hidden_field :id, :value => item.id %> <br />
<% end %>
<% end %>
<p><%= submit_tag "Submit" %></p>
<% end %>
Thanks.
Answering my own question since no one else did: I got method B to work with a very minor tweak. All it needed was parentheses around the value after “include?”, like so:
if team_ids.include?(team.id) == false.
I figured this out by playing with each line of code in the rails console.
Method A may work as well but since I got method B to work, I haven’t yet tried it.
UPDATE: method A also works