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 = => [])

  def create
    @company =[:company])

      redirect_to root_path, notice: I18n.t(:message_company_created)
      render :action => "new"

  def edit
    @company = Company.find(params[:id])

  def update
    @company = Company.find(params[:id])

    if @company.update_attributes(params[:company])
      redirect_to root_path, :notice => I18n.t(:message_company_updated)
      render :action => "edit"


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 %>
  <% 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? Thanks!


I think you should change your new action to:

def new
  @company =

See docs for further information. Then I think you have to add subscription_attributes to the attr_accessible list of your Company definition.

Need Your Help

Set shell's working directory to the current file opened in vim

bash vim cygwin working-directory

I am using Windows gVim and I am trying to invoke commands to run on cygwin's bash. It is working, but the working directory is set to $HOME every time. Would it possible to set to the current file's

Ruby on Rails and multi-core CPUs

ruby-on-rails ruby

I have been doing some test on my Pentium D (an old dual core CPU). As far as I understood Ruby was single threaded, so I have a hard time understanding why both cores are utilized ot the max (100%...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.