【问题标题】:Form helpers for nested attributes has_many through in rails 4rails 4 中嵌套属性 has_many 的表单助手
【发布时间】: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


    【解决方案1】:

    在表单构建器上使用 collection_select 助手。

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

    【讨论】:

    • 谢谢!完美运行。
    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多