الحصول على حقول_للعمل معها_العديد من العلاقات
-
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
ومع ذلك ، في النموذج ، عندما أحاول الحقول ، لا أحصل على أي شيء:
<% f.fields_for :scores do |builder| %>
<p>
<%= builder.label :score %><br />
<%= builder.text_field :score %>
</p>
<% end %>
ماذا أفعل خطأ?
المحلول
اتضح في القضبان 3، أحتاج إلى استخدام <٪= الحقول_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