Search code examples
ruby-on-railsruby-on-rails-3nested-attributes

Nested attributes for one-to-one relation


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:

  • The name field only shows in the edit form when a company already has a subscription, it doesn't show when adding a new company
  • When editing a company and changing the name field of the subscription, the change is not saved.

What am I doing wrong here?

I'm using version 3.1 of Rails


Solution

  • 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.