Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

ruby - Find records with multible column name in Rails

I have table Offer who have one OfferDescription dependence with activities stores like this:

t.boolean "discovery", default: false
t.boolean "meeting_animals", default: false
t.boolean "milking_animals", default: false
t.boolean "tasting", default: false
t.boolean "birth_animal", default: false
t.boolean "stroll", default: false
t.boolean "harvest", default: false
t.boolean "craft", default: false

My users can search Offers by activities, its ok when they select only one activity i did the request like this

activity = params[:activity].gsub(/'/, '')

.joins(:address, :offer_description)
.where("max_people_count >= ? AND offer_descriptions.#{activity}=?", peopleCount, true)
.near(location, distance, unit: :km)

But how i can do properly when they select multiple activities to find Offers who have this activity OR another one ?

The way the OfferDescription table was made look little bit strange for me

question from:https://stackoverflow.com/questions/66062512/find-records-with-multible-column-name-in-rails

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One solution can be

I assume for multiple activities we will get it in an array.

activities = ['discovery', 'meeting_animals']
activity_query = activities.each_with_object([]).do |activity, query|
  query << "offer_descriptions.#{activity} = :flag"
end.join(" OR ")

.joins(:address, :offer_description)
.where("max_people_count >= ? AND " + activity_query, 
       peopleCount, flag: true)
.near(location, distance, unit: :km)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...