Ruby on rails 带轨道的嵌套窗体
我在rails3.2应用程序中有一个投诉表格,它同时还建立了一个新的公司和分支机构。这一切都很好,但我想在分支表中将该公司的id存储为外键Company\u id 这是我的投诉控制员:Ruby on rails 带轨道的嵌套窗体,ruby-on-rails,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3.2,我在rails3.2应用程序中有一个投诉表格,它同时还建立了一个新的公司和分支机构。这一切都很好,但我想在分支表中将该公司的id存储为外键Company\u id 这是我的投诉控制员: def new @complaint = Complaint.new @complaint.build_company @complaint.build_branch(:company_id => '#Trying to set the company ID here')
def new
@complaint = Complaint.new
@complaint.build_company
@complaint.build_branch(:company_id => '#Trying to set the company ID here')
respond_to do |format|
format.html # new.html.erb
format.json { render json: @complaint }
end
end
我可以在
:company\u id=>
之后放置什么来分配上面创建的对象的id?不是这样吗
@complaint.build_branch(:company_id => @complaint.company_id)
问题似乎是由于未保存的公司对象&投诉对象。你没有概述模型的细节,但我想
@complaint = Compplaint.create(#Whatever parameters are required)
company = @complaint.companies.create() #Assuming has_many relationship
@complaint.branches.create(:comapny_id => company.id)
create保存记录并生成id,其中as build和new不保存记录
您还应该探索,在您的模型中有许多:到。解决方案是将以下代码添加到创建操作中
def create
...
@complaint.branch.company = @complaint.company
@complaint.save
...
end
这将不起作用,因为
@complaint.company
是一个新记录,也是基于同一请求生成的。您不能在未保存的实例上使用build设置外键。保存时它将被覆盖。在\u create操作之后,是否需要某种来执行此操作?您是否查看过为此使用accepts\u nested\u attributes\u和nested forms?