gpt4 book ai didi

ruby-on-rails - 在一个 POST 中创建父对象和子对象的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-04 05:57:47 25 4
gpt4 key购买 nike

我有两个应用程序,App1 和 App2。 App1 将 JSON 负载发布到 App2,其中包含父对象和子对象的数据。如果父对象已经存在于 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

像这样创建/更新父对象感觉很脏。有没有更好的方法来解决这个问题?谢谢!

最佳答案

首先,您需要在模型中创建关联,然后包含 accepts_nested_attributes_for在你的 parent 身上。

使用在模型中创建的关联,您应该能够非常轻松地操纵关系,因为您会自动获得许多用于管理关系的方法。例如,您的父/子模型可能如下所示:

在您的父模型中:

class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children

在您的 Child 模型中:
class Child < ActiveRecord::Base
belongs_to :parent

然后,您应该能够像这样在 Controller 中建立关联:
def new
@parent = Parent.children.build
end

def create
@parent = Parent.children.build(params[:parent])
end

然后,nested_attributes 属性将允许您通过操作父级来更新子级的属性。

这是有关该主题的 Rails API: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

关于ruby-on-rails - 在一个 POST 中创建父对象和子对象的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com