爲什麼lambda在rails範圍內傳遞?爲什麼不只是一個典型的街區?例如:爲什麼lambda在導軌範圍內?
scope :by_age, lambda do |age|
joins(:profile).where('profile.age = ?', age) unless age.nil?
end
感謝
爲什麼lambda在rails範圍內傳遞?爲什麼不只是一個典型的街區?例如:爲什麼lambda在導軌範圍內?
scope :by_age, lambda do |age|
joins(:profile).where('profile.age = ?', age) unless age.nil?
end
感謝
據我所知,範圍可以通過使用拉姆達帶參數。
但它是一樣的。您只是使用do ... end語法而不是{}。
{}和做...結束它只是兩種不同的語法,但你可以使用你喜歡的。 另外,lambda也有兩種不同的語法。 一,由你提出,二:
-> { ... your_code ... }
或參數:
->(arg) { ... your_code... }
這第二個語法看起來在範圍很漂亮。
scope :by_age, ->(age) { joins(:profile).where('profile.age = ?', age) unless age.nil? }
對於命名範圍,block參數用於擴展。要使用查詢塊,必須將其作爲標準參數傳遞(使用lambda
)