{ where(transmissio-6ren">
gpt4 book ai didi

ruby-on-rails - 可以在 Rails 中有条件地链接作用域吗?

转载 作者:行者123 更新时间:2023-12-03 15:05:27 24 4
gpt4 key购买 nike

考虑这段代码:

class Car
scope :blue, -> { where(color: "blue") }
scope :manual, -> { where(transmission: "manual") }
scope :luxury, -> { where("price > ?", 80000) }
end

def get_cars(blue: false, manual: false, luxury: false)
cars = Car.all
cars = cars.blue if blue
cars = cars.manual if manual
cars = cars.luxury if luxury
end

有没有办法像 Car.blue.manual.luxury 那样有条件地链接这些作用域? IE。只有参数为真时才作用域?

最佳答案

您可以使用 yield_self( read more here ),这是 ruby​​ 2.5 为它添加的新功能。

在你的例子中:

class Car
scope :blue, -> { where(color: "blue") }
scope :manual, -> { where(transmission: "manual") }
scope :luxury, -> { where("price > ?", 80000) }
end

def get_cars(blue: false, manual: false, luxury: false)
cars = Car.all
.yield_self { |cars| blue ? cars.blue : cars }
.yield_self { |cars| manual ? cars.manual : cars }
.yield_self { |cars| luxury ? cars.luxury : cars }
end

关于ruby-on-rails - 可以在 Rails 中有条件地链接作用域吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807741/

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