Hom*_*ith 5 nested-attributes ruby-on-rails-3 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
Run Code Online (Sandbox Code Playgroud)
def new
@game = Game.new
end
Run Code Online (Sandbox Code Playgroud)
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
为什么位置字段(城市)没有出现在表单中?我没有收到任何错误.我错过了什么?
好吧我不确定你是否想要选择一个现有的位置与名气联系,或者你是否希望为每个游戏创建一个新的位置.
假设这是第一个场景:
更改游戏模型中的关联,以便游戏属于某个位置.
class Game < ActiveRecord::Base
validates_presence_of :sport_type
belongs_to :location
accepts_nested_attributes_for :location
end
Run Code Online (Sandbox Code Playgroud)
您可能需要通过迁移向您的Game模型添加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
Run Code Online (Sandbox Code Playgroud)
如果您还没有game_id字段,则需要将其添加到位置模型中.
然后在您的控制器中,您需要构建一个位置,以便显示嵌套的表单字段:
def new
@game = Game.new
@location = @game.build_location
end
Run Code Online (Sandbox Code Playgroud)