![](/img/trans.png)
[英]Rails 4 with simple_form_for, has_many through and nested attributes
[英]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可以為特定的Sport創建/編輯Season。
我以這種方式工作:
= 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
預先感謝,瓦迪姆
在表單構建器上使用collection_select
幫助器。
builder.collection_select(:sport_id, Sport.all, :id, :name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.