Nested attributes for one-to-one relation

≡放荡痞女 提交于 2019-12-25 02:18:51

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/8339086/nested-attributes-for-one-to-one-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!