gpt4 book ai didi

ruby-on-rails - 什么方法将从类方法返回 ActiveRecord 所有者对象?

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

假设我的用户有元素:

class User < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :user
end

现在我想为项目添加一个类方法来创建自定义记录:

def self.create_personalized
create description: "#{user.name}' item"
end

当然,因为这是一个类方法,user 是未定义的。但是如果我使用 user.items.create_personalized 调用它,那么就会有一个通过关系关联的用户。我知道 Item.create_personalized 知道用户,因为它有效:

def self.create_personalized
item = create
item.update_attribute :description, "#{item.user.name}'s item"
end

但显然这不是访问所有者对象的最佳方式。什么是正确的方法?

最佳答案

如果你这样做

Item.scope_attributes

然后您将获得当前范围内适用于项目的任何属性的哈希值。如果您调用 create,就会从范围中提取这些内容。这些是数据库级别的属性,因此您将获得用户 ID 而不是用户本身。

关于ruby-on-rails - 什么方法将从类方法返回 ActiveRecord 所有者对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35041353/

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