嵌套属性的表单助手has_many通过rails 4

时间:2015-03-21 18:34:54

标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-attributes

我有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

然而,并没有将任何运动标记为&#34;选择&#34;。我不知道取代什么&#34;:sport_id&#34;在选项中。

我没有使用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

提前致谢, 瓦迪姆

1 个答案:

答案 0 :(得分:0)

在表单构建器上使用collection_select帮助程序。

builder.collection_select(:sport_id, Sport.all, :id, :name)