问题描述
我有两个应用程序,App1 和 App2.App1 将 JSON 负载发布到 App2,其中包含父对象和子对象的数据.如果父对象已经存在于 App2 中,那么如果有任何更改,我们更新父记录并在 App2 中创建子记录.如果App2中不存在父对象,我们需要先创建它,然后创建子对象并将两者关联起来.现在我是这样做的:
class ChildController定义创建@child = Child.find_or_initialize_by_some_id(params[:child][:some_id])@child.parent = Parent.create_or_update(params[:parent])如果@child.update_attributes(params[:child])做一点事别的渲染:json =>@child.errors, :status =>500结尾结尾结尾
像这样创建/更新父对象感觉很脏.有没有更好的方法来解决这个问题?谢谢!
首先,您需要在模型中创建关联,然后在父级中包含 accepts_nested_attributes_for
.>
使用在模型中创建的关联,您应该能够非常轻松地操纵关系,因为您会自动获得许多用于管理关系的方法.例如,您的父/子模型可能如下所示:
在您的父模型中:
class Parent <ActiveRecord::Basehas_many :儿童accepts_nested_attributes_for :children
在您的孩子模型中:
class Child ActiveRecord::Base归属地:父母
然后,您应该能够像这样在控制器中建立关联:
def new@parent = Parent.children.build结尾定义创建@parent = Parent.children.build(params[:parent])结尾
然后,nested_attributes 属性将允许您通过操作父级来更新子级的属性.
这是有关该主题的 Rails API:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
I have two applications, App1 and App2. App1 posts a JSON payload to App2 that includes data for a parent and child object. If the parent object already exists in App2, then we update the parent record if anything has changed and create the child record in App2. If the parent object does not exist in App2, we need to first create it, then create the child object and associate the two. Right now I'm doing it like this:
class ChildController
def create
@child = Child.find_or_initialize_by_some_id(params[:child][:some_id])
@child.parent = Parent.create_or_update(params[:parent])
if @child.update_attributes(params[:child])
do_something
else
render :json => @child.errors, :status => 500
end
end
end
Something feels dirty about creating/updating the parent like that. Is there a better way to go about this? Thanks!
As a starting point, you'll want to create the association in your model, then include accepts_nested_attributes_for
on your Parent.
With the associations created in your model, you should be able to manipulate the relationship pretty easily, because you automatically get a host of methods intended to manage the relationship. For example, your Parent/Child model might look something like this:
In your Parent model:
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
In your Child model:
class Child < ActiveRecord::Base
belongs_to :parent
Then, you should be able to build associations in your controller like this:
def new
@parent = Parent.children.build
end
def create
@parent = Parent.children.build(params[:parent])
end
The nested_attributes property will then allow you to update attributes of the Child by manipulating the Parent.
Here is the Rails API on the topic: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
这篇关于在一个 POST 中创建父对象和子对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!