How do I solve the following issue:
I want to add a new row to the table submitted_pictures, which is linked as follows:
game.rb
has_many :rounds
has_many :participants, :dependent => :destroy
has_many :submitted_pictures, :through => :rounds
has_many :users, :through => :participants
accepts_nested_attributes_for :participants
accepts_nested_attributes_for :rounds, :reject_if => :all_blank
round.rb
belongs_to :game
has_many :submitted_pictures, :dependent => :destroy
accepts_nested_attributes_for :submitted_pictures
submitted_picture.rb
has_one :round
has_one :game, :through => :rounds
belongs_to :user
So I could call:
<% @user.games.rounds.last.submitted_pictures.each do |blabla| %><% end>
I made a complex form using:
<%= form_for(@game) do |f| %>
<%= f.fields_for :round do |ff| %>
<%= ff.fields_for :submitted_pictures do |fff| %>
<%= fff.label :flickr_id %>
<%= fff.text_field :flickr_id %>
<% end %>
<% end %>
<%= f.submit "Submit Picture", class: "btn btn-primary" %>
<% end %>
Hoping to add a new submitted_picture with the flickr_id (which holds a httplink for now), linked to the the current game (@game).
I’ve been trying several things to update it but it doesnt seem to budge: (the update_attributes is totally wrong I see now :p)
def update
@game = Game.find(params[:id])
if @game.rounds.last.submitted_pictures.update_attributes(params[:id])
flash[:success] = "Pic Submitted!"
else
render :action => 'new'
end
end
Also
def update
@game = Game.find(params[:id])
if @game.save
flash[:success] = "Pic Submitted!"
redirect_to games_path
else
render :action => 'new'
end
end
I can’t get it to work. I’m getting all kinds of errors, so instead of noting them all here I thought it would be best to ask for the best solution.
So in short, I’m wanting to add a submitted_picture to the latest round (most recent created_at) of the game.
I think nesting everything in a game form is making things unnecessarily complicated for you. If I understand correctly, you want to create a new submitted_picture and it needs to have a game selected. The round is not directly selected, but is just the latest for the game. (this sounds like a suspicious assumption–but it does keep things simpler so I’ll roll with it)
So just make a new submitted_picture form, and add in a game select.
In your handler, pull the latest round from the game and merge that round into your params to save the new picture.
Does that do what you want?