我有两个应用程序,App1和App2。 App1向App2发布JSON有效负载,其中包含父对象和子对象的数据。如果父对象已经存在于App2中,那么我们会更新父记录(如果有任何更改)并在App2中创建子记录。如果父对象在App2中不存在,我们需要先创建它,然后创建子对象并将它们关联起来。现在我这样做:
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
像这样创建/更新父母感觉很脏。有没有更好的方法来解决这个问题?谢谢!
答案 0 :(得分:4)
作为一个起点,您需要在模型中创建关联,然后在您的父级中包含accepts_nested_attributes_for
。
通过在模型中创建关联,您应该能够非常轻松地操作关系,因为您会自动获得一系列用于管理关系的方法。例如,您的父/子模型可能如下所示:
在您的父模型中:
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
在您的儿童模特中:
class Child < ActiveRecord::Base
belongs_to :parent
然后,您应该能够在控制器中构建关联,如下所示:
def new
@parent = Parent.children.build
end
def create
@parent = Parent.children.build(params[:parent])
end
然后,nested_attributes属性允许您通过操作Parent来更新Child的属性。
以下是有关主题的Rails API:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
答案 1 :(得分:1)
使用accept_nested_attributes_for
处理父子关系。这是一篇博文,可以帮助您http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/