嵌套属性的表单助手 has_many 到 rails 4
Form helpers for nested attributes has_many through in rails 4
我有 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
我想创建一个表格,以便您可以编辑 Spot create/edit 特定运动的季节。
我是这样工作的:
= 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
但是它不会将任何运动标记为 "selected"。我不知道在选项中用“:sport_id”代替什么。
我在没有 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
提前致谢,
瓦迪姆
在表单生成器上使用 collection_select
助手。
builder.collection_select(:sport_id, Sport.all, :id, :name)
我有 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
我想创建一个表格,以便您可以编辑 Spot create/edit 特定运动的季节。
我是这样工作的:
= 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
但是它不会将任何运动标记为 "selected"。我不知道在选项中用“:sport_id”代替什么。
我在没有 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
提前致谢, 瓦迪姆
在表单生成器上使用 collection_select
助手。
builder.collection_select(:sport_id, Sport.all, :id, :name)