Reputation: 6612
I have a Company which has one Subscription. Now I want a form to add or edit the company and the subscription, so I use "accepts_nested_attributes_for". This is (part of) the Company model:
has_one :subscription, :dependent => :destroy
accepts_nested_attributes_for :subscription
This is (part of) the Subscription model:
belongs_to :company
In the controller I have this:
def new
@company = Company.new(:subscription => [Subscription.new])
end
def create
@company = Company.new(params[:company])
if @company.save
redirect_to root_path, notice: I18n.t(:message_company_created)
else
render :action => "new"
end
end
def edit
@company = Company.find(params[:id])
end
def update
@company = Company.find(params[:id])
if @company.update_attributes(params[:company])
redirect_to root_path, :notice => I18n.t(:message_company_updated)
else
render :action => "edit"
end
end
And the form looks like this:
<%= f.fields_for(:subscription) do |s_form| %>
<div class="field">
<%= s_form.label I18n.t(:subscription_name) %>
<%= s_form.text_field :name %>
</div>
<% end %>
This gives 2 problems:
What am I doing wrong here?
I'm using version 3.1 of Rails
Upvotes: 0
Views: 1607
Reputation: 20724
I think you should change your new action to:
def new
@company = Company.new
@company.build_subscription
end
See docs for further information. Then I think you have to add subscription_attributes
to the attr_accessible list of your Company definition.
Upvotes: 2