【发布时间】:2015-03-22 04:41:45
【问题描述】:
我有 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,您可以为特定运动创建/编辑赛季。
我是这样工作的:
= 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
但是,它不会将任何运动标记为“已选择”。我不知道在选项中用什么替换 ":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
提前致谢, 瓦迪姆
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-attributes