Getting fields_for to work with has_many relationship
-
13-11-2019 - |
Question
I'm having trouble generating a nested model form.
Here are my models:
class Workout < ActiveRecord::Base
has_many :scores
has_many :users, :through => :scores
accepts_nested_attributes_for :scores
end
class Score < ActiveRecord::Base
belongs_to :user
belongs_to :workout
end
class User < ActiveRecord::Base
has_many :scores
has_many :workout, :through => :scores
end
In the Workout controller, here's what I have for the new action:
def new
@workout = Workout.new
3.times { @workout.scores.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @wod }
end
end
However, in the form, when I try fields_for, I don't get anything:
<% f.fields_for :scores do |builder| %>
<p>
<%= builder.label :score %><br />
<%= builder.text_field :score %>
</p>
<% end %>
What am I doing wrong?
Solution
It turns out in Rails 3, I need to use <%= fields_for ... %> instead of <% fields_for ... %>.
OTHER TIPS
Try adding the following to your Workout
model:
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores
If you want to make sure that a score doesn't get built unless is it valid, and that is can be destroyed through the relationship you can expand to:
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores, reject_if: proc { |a| a[:field].blank? }, allow_destroy: true
validates_associated :scores
Just switch :field
with a relevant field that is required for a score to be created.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow