Rodrigo Zurek
Rodrigo Zurek

Reputation: 4575

rails nested model forms has_one association

Im using simple_form gem and i need to do a nested form but im having trouble here is some code:

i have two models:

Apiphones:

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

Stores:

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

and in my view:

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

but nothing is showing, any ideas?

Upvotes: 5

Views: 10032

Answers (2)

jvnill
jvnill

Reputation: 29599

using fields_for in conjunction with accepts_nested_attributes assumes that the records are initialized. This means that, using your models, @store.apiphone should not be nil when the form is generated. The way to solve this issue is making sure that apiphone is initialized and associated to @store (both new and edit actions).

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

Upvotes: 22

zolter
zolter

Reputation: 7160

I think you forget build apiphone in your controller, for example:

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

Upvotes: 3

Related Questions