【问题标题】:rails nested model forms has_one associationrails 嵌套模型表单 has_one 关联
【发布时间】:2013-08-26 06:23:08
【问题描述】:

我正在使用 simple_form gem,我需要做一个嵌套表单,但我遇到了一些代码:

我有两种型号:

APIphones:

class Apiphone < ActiveRecord::Base
  attr_accessible :key, :phone
  validates_presence_of :phone
  belongs_to :store
end

商店:

class Store < ActiveRecord::Base
  has_one :apiphone
  accepts_nested_attributes_for :apiphone
end

在我看来:

<%= simple_form_for [@group,@store] do |f| %>
    <%= f.simple_fields_for :apiphone do |ph| %>
      <%= ph.input :phone %>
    <% end %>
<% end %>

但什么都没有显示,有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    fields_foraccepts_nested_attributes 结合使用假定记录已初始化。这意味着,使用您的模型,@store.apiphone 在生成表单时不应该是nil。解决此问题的方法是确保 apiphone 已初始化并关联到 @store(新操作和编辑操作)。

    def new
      @store = Store.new
      @store.build_apiphone
    end
    

    【讨论】:

    • 非常感谢!让我困惑了很长时间
    【解决方案2】:

    我想你忘记在你的控制器中构建 apiphone,例如:

    def new
     ...
     @store.build_apiphone
     ...
    end
    

    【讨论】:

    • 我对此不确定,但.build 用于has_many。因为这是has_one,你需要使用build_apiphone
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多