简体   繁体   中英

Build search query from array in Rails

I have a model Person and a datatable PersonCode . Now in my controller, I want to make a search for multiple codes. What would be the right way to do this?

I tried to define a class method on Person

def self.code_filter(codes)
    joins(:PersonCode)
    codes.each do |code|
        where("rank > 1 AND person_code.code LIKE '%" + code +"%'")
end

But when I call this class method in my controller with, say ['Z','Q']

Person
    .code_filter(my_array)
    .another_query_method(some_value)

I get the the following error message: "undefined method `another_query_method' for ["Z", "Q"]:Array"

I kinda see why this isn't working but how can I make a correctly concatenated query with these SQL statements?

Because of each method.

This method returns the original Array object.

[1,2,3].each {|i| p i + 1}

returns [1,2,3].

Use Array#map and you'll get an array of relations

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