Getting fields to work with has_many relationships

I had a problem creating a nested model.

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 is what I have for a 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 get nothing:

<% f.fields_for :scores do |builder| %>
    <p>
        <%= builder.label :score %><br />
        <%= builder.text_field :score %>
    </p>
<% end %>

What am I doing wrong?

+5
source share
2 answers

It turns out in Rails 3, I need to use <% = fields_for ...%> instead of <% fields_for ...%>.

+6
source

Try adding the following to your model Workout:

attr_accessible :scores_attributes

accepts_nested_attributes_for :scores

If you want to make sure that the assessment will not be built if it is not valid, and it can be destroyed through a relationship that you can expand, follow these steps:

attr_accessible :scores_attributes

accepts_nested_attributes_for :scores, reject_if: proc { |a| a[:field].blank? }, allow_destroy: true
validates_associated :scores

:field , .

0

All Articles