I’ve got a pickem object that has one result. I’m having an issue getting the result to save properly to the database.
pickems_controller.rb
def results
@pickem = Pickem.find params[:id]
# @pickem.result = @pickem.build_result if @pickem.result.blank?
@pickem.result = Result.new
end
def update_results
@pickem = Pickem.find params[:id]
@pickem.result = Result.new params[:pickem][:result_attributes]
if @pickem.result.update_attributes params[:pickem][:result_attributes]
redirect_to edit_pickem_results_path(@pickem), :notice => 'The results have been successfully updated.'
else
render "edit"
end
end
results.html.erb
<%= simple_form_for @pickem, :url => edit_pickem_results_path(@pickem), :method => :put, do |f| %>
<%= f.simple_fields_for :result do |r| %>
<%= r.input :first_name %>
...
<% end %>
<%= f.submit :class => 'btn btn-success', :label => 'Submit Results' %>
<% end %>
pickem.rb
has_one :result, :dependent => :destroy
accepts_nested_attributes_for :result
result.rb
belongs_to :pickem
I was initially using the build_result code that is commented out in the controller but had to back out of that. With build_result a result record was saved to the database the instant somebody clicked into the results form. There are rules in place in the application that don’t allow users to make any picks if a result has been entered. So even if a user clicked into the result form but didn’t submit, the result was still being created.
How can I build my form and save the result record only when the user clicks save, and not when the form is loaded? The current solution I’ve pasted above does not work. It saves a result record with the appropriate foreign key but never gets the form data. If I dump @pickem.result the correct form data is in the result object, I just can’t get it to save right. Other solutions I’ve tried save the form data correctly but have a foreign key of 0.
EDIT:
For whatever reason @pickem.result = Result.new was still saving a record to the database so I changed it to @result = Result.new and updated the form as follows:
<%= simple_form_for @result, :url => edit_pickem_results_path(@pickem), :method => :put, do |r| %>
<%= r.input :first_name %>
<%= r.submit :class => 'btn btn-success', :label => 'Submit Results' %>
<% end %>
Then using the suggestion from Chuck W of @result = @pickem.result.build params[:result], I get undefined methodbuild’ for nil:NilClass`.
pickems_controller.rb
Then, your view should look something like this:
You might have to play around with how the parameters are being passed back to the update_results action (I’m pretty new to rails), but I think you get the gist of it.