![](/img/trans.png)
[英]Rails: getting an average from all the instances of a model from birthdate
[英]Rails 4: Return all instances from a where call
我在發票表中有一個狀態整數列
def change
create_table :invoices do |t|
t.integer :status
end
end
我找到這樣的發現
def find_status(status)
Invoice.where(status: status)
end
當我想查找狀態為1的所有發票時,這非常好。
但是,有時我想使用find_status方法返回所有發票嗎?
我可以用if語句解決這個問題,但是我的問題是;
我可以將某些東西傳遞給find_status方法,該方法將返回所有發票嗎?
PS:復習此問題后,我了解到是否有人會提出針對該問題的其他解決方案的建議。 請將此問題視為“概念教授的問題”
您可以將數組或范圍放入方法調用中,前提是您沒有數百種狀態,但無法抵抗誘惑-如果您想要它們全部,我將避免方法調用而只做Invoice.all
這幾乎是不可能做到這一點的where
不支持在這種情況下通配符和選項,如巨大的范圍內產生非常不干凈的代碼。 但是您可以使用Invoice.all
調用而不是調用此方法。
如果您堅持對兩者使用相同的方法,則可以像下面那樣更改find_status方法。
def find_status(status = nil)
status.nil? ? Invoice.all.to_a : Invoice.where(status: status)
end
絕對不可能! 希望我們能夠做到,這將是一個真正的安全問題。 不過,如果您不介意缺乏安全性,仍然可以編寫類似
def find_status(status)
Invoice.where("status = #{status}")
end
接着
find_status(1) #=> All invoices with the status 1
find_status('status') #=> All invoices :)
但是再次,我所做的就是利用缺乏安全性! 如您所說,您可以輕松地使用if或if? 條件陳述
其實! 您可以這樣做:
find_status Invoice.pluck(:status)
它的工作原理沒有改變您的方法:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.