一对一关系的嵌套属性 [英] Nested attributes for one-to-one relation
问题描述
我有一家拥有一个订阅的公司.现在,我想要一个表单来添加或编辑公司和订阅,因此我使用"accepts_nested_attributes_for".这是公司模型的一部分(部分):
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
表单如下:
<%= f.fields_for(:subscription) do |s_form| %>
<div class="field">
<%= s_form.label I18n.t(:subscription_name) %>
<%= s_form.text_field :name %>
</div>
<% end %>
这带来2个问题:
- 仅当公司已经有订阅时,名称字段才显示在编辑表单中,而在添加新公司时则不显示
- 在编辑公司并更改订阅的名称字段时,更改不会保存.
我在这里做错了什么?
What am I doing wrong here?
我正在使用3.1版的Rails
I'm using version 3.1 of Rails
推荐答案
我认为您应该将新操作更改为:
I think you should change your new action to:
def new
@company = Company.new
@company.build_subscription
end
有关更多信息,请参见文档.然后,我认为您必须将subscription_attributes
添加到公司的 attr_accessible 列表中定义.
See docs for further information. Then I think you have to add subscription_attributes
to the attr_accessible list of your Company definition.
这篇关于一对一关系的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!