gpt4 book ai didi

ruby-on-rails - 在 Rails 模型中动态生成范围

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:03 25 4
gpt4 key购买 nike

我想动态生成作用域。假设我有以下模型:

class Product < ActiveRecord::Base
POSSIBLE_SIZES = [:small, :medium, :large]
scope :small, where(size: :small)
scope :medium, where(size: :medium)
scope :large, where(size: :large)
end

我们可以用基于 POSSIBLE_SIZES 常量的东西替换 scope 调用吗?我认为我违反了 DRY 以重复它们。

最佳答案

你可以做

class Product < ActiveRecord::Base
[:small, :medium, :large].each do |s|
scope s, where(size: s)
end
end

但我个人更喜欢:

class Product < ActiveRecord::Base
scope :sized, lambda{|size| where(size: size)}
end

关于ruby-on-rails - 在 Rails 模型中动态生成范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14061595/

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