gpt4 book ai didi

mysql - Rails 最佳实践 : Constants for model ids, 或 find_by 或 where 查询?

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:10 26 4
gpt4 key购买 nike

我有一种情况需要做出最佳实践决定,这将影响我系统的很大一部分。有许多不同的 has_many through: 关系,我将经常查询它们以查看特定项目是否存在并附加到另一个项目。

class User
has_many :user_skills
has_many :skills, through: :user_skills
end

class Skill
has_many :user_skills
has_many :users, through: :user_skills
end

class UserSkill
belongs_to :skill
belongs_to :user
end

系统中将有数以千计的用户,可以与任意数量的技能组合,其中大约有200+。我试图弄清楚查询用户 以查明他/她是否拥有特定技能 的最快、最有效的方法是什么。我倾向于常量,因为 ID 在开发、测试和生产中显然会有所不同,而且只需加载一次而不是每次都搜索非索引名称会很好。

<强>1。 #find_by (:name)

@user.skills.find_by(name: 'Ruby-on-Rails').present?

<强>2。 #where ('名字...')

@user.skills.where("name = 'Ruby-on_rails'").present?

<强>3。常量 + #find_by (:id)常量将在应用程序加载时使用 #const_set 动态设置,因此将始终存储 200 多个常量

RUBY_ON_RAILS = 41
RUBY = 42
PHP = 45

@user.skills.find_by(id: RUBY_ON_RAILS).present?

<强>4。常量 + #pluck (:id)与上面相同的常量

@user.skills.pluck(:id).include?(RUBY_ON_RAILS)

<强>5。 ???我没有想到的更好的方法

最佳答案

有一个更好的方法:

@user.skills.exists?(name: 'Ruby-on-Rails')

它也适用于关系:

@user.skills.where(name: 'Ruby-on-Rails').exists?

关于mysql - Rails 最佳实践 : Constants for model ids, 或 find_by 或 where 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982638/

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