简体   繁体   中英

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.

But, sometimes I want to the find_status method return all invoices?

I could solve this with a if statement, but my question is;

Can I pass something into the find_status method that will return all invoices?

PS: After reviewing this question I understand if someone get the temptation to suggest other solutions to the problem. 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. But you might use Invoice.all call instead of calling this method.

You can change your find_status method like below if you insist on using the same method for both.

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 ? condition statement

Actually ! You can do that:

find_status Invoice.pluck(:status)

It works without changing your method :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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