Is it possible to create an association within a simple_fields_for object?
<%= simple_form_for(@rooftop) do |f| %>
<div class="inputs">
<%= f.input :name %>
<%= f.simple_fields_for "address", @address do |a| %>
<%= a.input :street %>
<%= a.association :state, :include_blank => false %>
<%= a.input :zip %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
simple_fields_for works pretty much the same way fields_for, it just uses SimpleForm builder, so you're able to do wathever you'd do without SimpleForm =).
This doesnt really answer my question. When going to this view I get an error
Association cannot be used in forms not associated with an object
My associations seem to be correct but creating an association will not return a valid object within the simple_form.
The models that I am using are rooftop
class Rooftop < ActiveRecord::Base
has_one :address
validates_presence_of :name, :on => :create,
:message => "cant be blank"
end
and address
class Address < ActiveRecord::Base
has_one :state
attr_accessible :street, :city, :state_id, :zip
validates_presence_of :street, :on => :create,
:message => "cant be blank"
end
From here, address has an association to a state model
class State < ActiveRecord::Base
belongs_to :country
has_many :addresses
attr_accessible :name, :country_id
validates_presence_of :name, :on => :create,
:message => "cant be blank"
validates_uniqueness_of :name, :scope => :country_id,
:message => "state for this country already exists"
end
The error message says there is no object associated do simple_fields_for. Does your @address variable exist? In most cases, you just need to build that variable through the association and call it like this:
# Controller
@rooftop.build_address
# View
<%= f.simple_fields_for :address do |a| %>
# a.input/association
<% end %>
I'm an idiot. I figured out the problem and you steered us in the right direction. Thanks a lot for your help :) and its a great plugin!
Nice! Thanks =)
Just for the records, with rails 4 you also need to have the accepts_nested_attributes_for in place.
@fwolfst That's accepts_nested_attributes_for (with an s after accept)
@tboyko Thanks. For future readers: Never mind, I corrected the relevant message already.
Most helpful comment
Just for the records, with rails 4 you also need to have the
accepts_nested_attributes_forin place.