鉴于以下情况:
Models
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 %>
为什么位置字段(城市)没有显示在表单中?我没有收到任何错误。我缺少什么?
好吧,我不确定您是否想要选择一个与名气相关的现有位置,或者您是否希望为每个游戏创建一个新位置。
假设是第一种情况:
更改游戏模型中的关联,以便游戏属于某个位置。
class Game < ActiveRecord::Base
validates_presence_of :sport_type
belongs_to :location
accepts_nested_attributes_for :location
end
您可能需要通过迁移将 location_id 字段添加到您的游戏模型中。
然后,您只需更改游戏模型本身的位置字段,而不是嵌套表单。
如果是第二种情况,并且您希望为每个游戏构建一个新位置,那么您将需要按如下方式更改模型:
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 字段,则需要将其添加到位置模型中。
然后在您的控制器中,您将需要构建一个位置以便显示嵌套表单字段:
def new
@game = Game.new
@location = @game.build_location
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)