Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 312
Rodrigo Zurek Avatar asked Aug 26 '13 06:08

Rodrigo Zurek


2 Answers

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
like image 105
jvnill Avatar answered Nov 16 '22 03:11

jvnill


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

def new
 ...
 @store.build_apiphone
 ...
end
like image 31
zolter Avatar answered Nov 16 '22 05:11

zolter