ruby-on-rails-3 – 嵌套属性未以简单形式显示
发布时间:2020-12-17 03:14:18 所属栏目:百科 来源:网络整理
导读:鉴于以下内容: 楷模 class Location ActiveRecord::Base has_many :gamesendclass Game ActiveRecord::Base validates_presence_of :sport_type has_one :location accepts_nested_attributes_for :locationend 调节器 def new @game = Game.new end 查看(
鉴于以下内容:
楷模 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 您可能需要通过迁移向您的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 如果您还没有game_id字段,则需要将其添加到位置模型中. 然后在您的控制器中,您需要构建一个位置,以便显示嵌套的表单字段: def new @game = Game.new @location = @game.build_location end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |