[英]Form helpers for nested attributes has_many through in rails 4
I have 3 models with has_many through association: 我有3个通过关联具有has_many的模型:
class Spot < ActiveRecord::Base
has_many :seasons
has_many :sports, through: :seasons
accepts_nested_attributes_for :sports, :seasons
end
class Sport < ActiveRecord::Base
has_many :seasons
has_many :spots, through: :seasons
end
class Season < ActiveRecord::Base
belongs_to :spot
belongs_to :sport
end
I want to create a form so that editing the Spot you can create/edit Season for particular Sport. 我想创建一个表格,以便编辑Spot可以为特定的Sport创建/编辑Season。
I've got it working this way: 我以这种方式工作:
= form_for([@country, @spot], :html => { :multipart => true }) do |f|
#some Rails code here
= f.fields_for :seasons do |builder|
= builder.select :sport_id, options_from_collection_for_select(Sport.all, :id, :name, :sport_id)
= builder.text_field :months
= builder.hidden_field :spot_id
However it doesn't mark any Sport as "selected". 但是,它不会将任何运动标记为“选定”。 I don't know what to substiture ":sport_id" for in the options.
我不知道在选项中使用“:sport_id”替代什么。
I've got it working properly without Rails form helpers, but it seems that could be done with helpers: 没有Rails表单帮助程序,它已经可以正常工作,但是似乎可以使用帮助程序来完成:
- @spot.seasons.each do |season|
= select_tag "spot[seasons_attributes][][sport_id]", options_from_collection_for_select(Sport.all, :id, :name, season.sport.id)
= hidden_field_tag 'spot[seasons_attributes][][id]', season.id
= text_field_tag 'spot[seasons_attributes][][months]', season.months
Thanks in advance, Vadim 预先感谢,瓦迪姆
在表单构建器上使用collection_select
帮助器。
builder.collection_select(:sport_id, Sport.all, :id, :name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.