简体   繁体   中英

ActiveRecord query using a two dimentional array

Can anyone help me in this issue, Like I have two dimensional array like this

array = [[1, 'go'], [15, 'flat']........] 

And I have table in the database called FeedPost, now in the 2D array the first element in each array means to a column user_id and the second one means to the column feed_type. Now I want to get all the records from that table that fulfills that array elements exactly matches to these exact column. in other word i wanted do something like that,

FeedPost.find_all_by_user_id_and_feed_type(array)

but unfortunately it shows following argument error.

ArgumentError: wrong number of arguments (1 for 2)

So anyone can help me in this issue please?

Install the any_of gem , then:

queries = array.map {|sub_array| FeedPost.where({ user_id: sub_array[0], feed_type: sub_array[1] }) }
FeedPost.where.any_of(*queries)

I think the best solution would be:

FeedPost.where(user_id: array.map(&:first)).where(feed_type: array.map(&:last))

this will split your array into two arrays, one containing the user_ids and one containing the feed_types, and query the feed posts accordingly using an IN SQL statement.

EDIT: this will bring any all records that have any combination of user_id and feed_type from the array. If you want only records that only satisfy both user_id and feed_type from a single item in the array, this won't work.

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