简体   繁体   English

Rails 4:从where调用返回所有实例

[英]Rails 4: Return all instances from a where call

I have a status integer column in a invoices table 我在发票表中有一个状态整数列

def change
  create_table :invoices do |t|
    t.integer   :status
  end
end

I do a find like this 我找到这样的发现

def find_status(status)
  Invoice.where(status: status)
end

This is great when I want to find all invoices with, say status 1. 当我想查找状态为1的所有发票时,这非常好。

But, sometimes I want to the find_status method return all invoices? 但是,有时我想使用find_status方法返回所有发票吗?

I could solve this with a if statement, but my question is; 我可以用if语句解决这个问题,但是我的问题是;

Can I pass something into the find_status method that will return all invoices? 我可以将某些东西传递给find_status方法,该方法将返回所有发票吗?

PS: After reviewing this question I understand if someone get the temptation to suggest other solutions to the problem. PS:复习此问题后,我了解到是否有人会提出针对该问题的其他解决方案的建议。 Please just look at this question as a "prof of concept kind of question" 请将此问题视为“概念教授的问题”

您可以将数组或范围放入方法调用中,前提是您没有数百种状态,但无法抵抗诱惑-如果您想要它们全部,我将避免方法调用而只做Invoice.all

It is nearly impossible to do that as where doesn't support wildcards in this scenario and options like huge range result in very unclean code. 这几乎是不可能做到这一点的where不支持在这种情况下通配符和选项,如巨大的范围内产生非常不干净的代码。 But you might use Invoice.all call instead of calling this method. 但是您可以使用Invoice.all调用而不是调用此方法。

You can change your find_status method like below if you insist on using the same method for both. 如果您坚持对两者使用相同的方法,则可以像下面那样更改find​​_status方法。

def find_status(status = nil)
  status.nil? ? Invoice.all.to_a : Invoice.where(status: status)
end

It is absolutely impossible ! 绝对不可能! And hopefully, that would be a real security issue if we could do that. 希望我们能够做到,这将是一个真正的安全问题。 Nevertheless, if you don't mind a lack of security, you can still write something like 不过,如果您不介意缺乏安全性,仍然可以编写类似

def find_status(status)
  Invoice.where("status = #{status}")
end

And then 接着

find_status(1) #=> All invoices with the status 1
find_status('status') #=> All invoices :)

But again, what I did was exploiting a lack of security ! 但是再次,我所做的就是利用缺乏安全性! And as you said, you could easily use an if or a ? 如您所说,您可以轻松地使用if或if? condition statement 条件陈述

Actually ! 其实! You can do that: 您可以这样做:

find_status Invoice.pluck(:status)

It works without changing your method :) 它的工作原理没有改变您的方法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM