rails嵌套模型表单has_one关联

时间:2013-08-26 06:23:09

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

我使用的是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 %>

但没有任何表现,任何想法?

2 个答案:

答案 0 :(得分:21)

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

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

答案 1 :(得分:3)

我认为您忘记了控制器中的构建apiphone,例如:

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