嵌套属性未以简单形式显示 [英] Nested attributes not showing up in simple form
问题描述
给出以下内容:
class Location < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
validates_presence_of :sport_type
has_one :location
accepts_nested_attributes_for :location
end
控制器
def new
@game = Game.new
end
查看(窗体)
<%= simple_form_for @game do |f| %>
<%= f.input :sport_type %>
<%= f.input :description %>
<%= f.simple_fields_for :location do |location_form| %>
<%= location_form.input :city %>
<% end %>
<%= f.button :submit %>
<% end %>
为什么位置字段(城市)没有显示在表格中?我没有任何错误.我想念什么?
Why the locations field (city) are not showing up in the form? I am not getting any error. What am I missing?
推荐答案
好吧,我不确定您是否要选择一个与名气相关的现有位置,或者是否希望为每个游戏创建一个新位置.
Ok I'm not sure if you are looking to pick an existing location to associate with the fame or if you are wishing to create a new location for each game.
假设这是第一种情况:
更改游戏模型中的关联,以使游戏属于某个位置.
Change the association in the Game model so that a game belongs to a location.
class Game < ActiveRecord::Base
validates_presence_of :sport_type
belongs_to :location
accepts_nested_attributes_for :location
end
您可能需要通过迁移将location_id字段添加到游戏模型中.
You may need to add a location_id field to your Game model via a migration.
然后,您将要更改游戏模型本身上的位置"字段,而不是嵌套表单.
Then instead of a nested form you are just going to be changing the Location field on the Game model itself.
如果是第二种情况,并且您希望为每个游戏建立一个新位置,那么您将需要按以下方式更改模型:
If it is the second scenario and you wish to build a new location for each game then you will need to change your models as follows:
class Location < ActiveRecord::Base
belongs_to :game
end
class Game < ActiveRecord::Base
validates_presence_of :sport_type
has_one :location
accepts_nested_attributes_for :location
end
如果您还没有一个game_id字段,则需要将其添加到位置模型中.
You will need to add a game_id field to the location model if you do not already have one.
然后,在您的控制器中,您将需要构建一个位置,以便显示嵌套的表单字段:
Then in your controller you will need to build a location in order to get the nested form fields to show:
def new
@game = Game.new
@location = @game.build_location
end
这篇关于嵌套属性未以简单形式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!