鉴于以下情况:
楷模
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
Controller
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 字段添加到您的游戏模型中。
然后,您只需更改 Game 模型本身的 Location 字段,而不是嵌套表单。
如果是第二种情况,并且您希望为每个游戏建立一个新位置,那么您需要按如下方式更改模型:
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 字段,则需要向位置模型添加一个字段。
然后在您的 Controller 中,您需要建立一个位置,以便让嵌套的表单字段显示:
def new
@game = Game.new
@location = @game.build_location
end
关于ruby-on-rails-3 - 嵌套属性未以简单形式显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10528582/