gpt4 book ai didi

ruby-on-rails - 嵌套属性并通过 Controller 添加属性?

转载 作者:行者123 更新时间:2023-12-02 07:00:45 25 4
gpt4 key购买 nike

由于这个问题很难描述,这是我能想到的最好的标题,所以这里是一些代码。

给定三个模型“ parent ”、“ child ”和“孙子”。

Parent <  ActiveRecord::Base
has_many :children
has_many :grandchildren
accepts_nested_attributes_for :child
end

Child < ActiveRecord::Base
belongs_to :parent
has_many :kids, :as => :grandchildren #this is just an example
accepts_nested_attributes_for :grandchild
end

Grandchild < ActiveRecord::Base
belongs_to :parent
belongs_to :child
end

我想将 current_user.id 添加到在 Parent#new 期间创建的子记录和孙记录。我现在使用隐藏字段,因为我找不到添加它们的好方法。

也许有人可以通过创建回调来在创建时添加 current_user.id 来提供帮助?无论如何,我从来没有运气将其纳入模型,但你很聪明。

想法?

最佳答案

嗯,一方面,我建议从父级到孙级(通过子级)建立一种 has_many :through 关系,反之亦然。有关详细信息,请参阅 the ActiveRecord Association Class Methods API 中的“关联连接模型”部分。

至于您的主要问题,就像您所说,回调可能就是您想要的。我认为类似的事情应该做到这一点(尽管这是未经测试的代码):

class Parent
# ...somewhere at the top...
before_create :set_current_user_on_descendants

# ...somewhere in the main class body...
# (I assume parent['current_user'] is passed in as a typical
# parameter, and thus self.current_user is already set.)
def set_current_user_on_descendants
children.each { |c| c.current_user = self.current_user }
grandchildren.each { |gc| gc.current_user = self.current_user }
end
end

有一些风格点可以采取不同的做法。例如,您可以定义一个返回子级 + 孙子级的“后代”方法并对其进行迭代,或者您可以在子级和孙级类上实现回调(在这种情况下,您可能希望将其拉出到模块中以获得最大干燥,尽管对于只有两个类的单行方法来说可能有点过大了)。根据您想要更新 current_user 的具体时间,您可能需要使用 before_save 或其他回调而不是 before_create - 您可以在 the ActiveRecord callbacks API 中找到可用回调的完整列表.

关于ruby-on-rails - 嵌套属性并通过 Controller 添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1976005/

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