fields_forがhas_many関係を扱うようにする
-
13-11-2019 - |
質問
ネストしたモデルフォームを生成するのに問題があります。
ここに私のモデルがあります:
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
.
ワークアウトコントローラでは、これが私が新しいアクションのために持っているものです:
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
.
しかし、fields_forを試すとき、私は何も得られません:
<% f.fields_for :scores do |builder| %>
<p>
<%= builder.label :score %><br />
<%= builder.text_field :score %>
</p>
<% end %>
.
私は何をしていますか?
解決
Rails 3では、<%fields_for ...%>。の代わりに<%= fields_for ...%>を使用する必要があります。
他のヒント
Workout
モデルに次のものを追加してみてください。
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores
.
スコアが有効でない限り、スコアが構築されないようにしたい場合は、展開することができます:
attr_accessible :scores_attributes
accepts_nested_attributes_for :scores, reject_if: proc { |a| a[:field].blank? }, allow_destroy: true
validates_associated :scores
.
スコアを作成するには、:field
を関連フィールドで切り替えるだけです。
所属していません StackOverflow