【问题标题】:Nested attributes not showing up in simple form嵌套属性未以简单形式显示
【发布时间】:2012-05-10 06:30:03
【问题描述】:

鉴于以下情况:

型号

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 %>

为什么位置字段(城市)没有显示在表单中?我没有收到任何错误。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails-3 nested-attributes simple-form


    【解决方案1】:

    好的,我不确定您是想选择一个现有的位置与名声相关联,还是希望为每个游戏创建一个新位置。

    假设是第一个场景:

    更改 Game 模型中的关联,使游戏属于某个位置。

    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 字段,则需要将其添加到位置模型。

    然后在您的控制器中,您将需要构建一个位置以显示嵌套的表单字段:

    def new
     @game = Game.new
     @location = @game.build_location 
    end
    

    【讨论】:

    • 如果我这样做,我会得到:未知属性:game_id
    • 它有效,但为什么我需要使用belongs_to而不是has_one??
    • 说一个游戏 HAS_ONE 位置意味着您希望位置表引用一个 game_id。但是,这与您的其他关联显示位置 HAS_MANY 游戏不一致,该关联会期望游戏桌包含 location_id。在我看来,一个游戏 BELONGS_TO 位置,它应该是保存 location_id 的表\
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    相关资源
    最近更新 更多