简体   繁体   中英

ransack match all associations

I have User model, has_many skills. I need to get users match all the selected skills. For example:

User A: Ruby, HTML, JavaScript. 
User B: Ruby
User C: Ruby, C++

When I search using the list of skills names or ids. I need get users have all values in this list. So, Search using Ruby & Javascript , I need to get User A .

The Problem if I used ransack gem skills_id_in , It'll return all users have Ruby Skill. The Query is as the following:

SELECT \"users\".* FROM \"users\" LEFT OUTER JOIN \"user_skills\" ON \"user_skills\".\"user_id\" = \"users\".\"id\" LEFT OUTER JOIN \"skills\" ON \"skills\".\"id\" = \"user_skills\".\"skill_id\" WHERE \"skills\".\"id\" IN (1, 3)

If it's not allowed in ransack. Can you help How make it in ActiveRecord & run in DB level ?

My Opinion: It's can't implement using ransack params , If you know Native Query to match all association, let me know?

I can't seem to find a way to query a CONTAINS directly through Postgres, but the following would work:

result = User.joins(:skills)

skills_names = ['Ruby', 'JavaScript']
skills_names.each do |skill_name|
  result = result.where('? = ANY(name)', skill_name)
end

If you know how many skills you're going to be querying ahead of time, you could combine them all into one query:

User.joins(:skills).where('? = ANY(name) AND ? = ANY(name)', 'Ruby', 'JavaScript')

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