search the records using two keys in two tables in rails -


i have models named user , service

user model has following columns: user_name , location_name

service model has following columns: user_location , service_name

now want search users residing in particular location , providing particular service.

the main problem user can provide more 1 service.

i have achieved functionality in following way:

serv1 = services.find_by_service_name(service_name)  res = [] serv1.each |s|    res.push s if s.user_location == location_name end 

can suggest better way?

user can provide more 1 service

that means user associated service model has_many relationship, i.e., models should like:

class user < activerecord::base   has_many :services   ## ...  end  class service < activerecord::base   belongs_to :user   ## ... end 

next, must have foreign_key user_id in services table.

now want search users residing in particular location , providing particular service.

you can achieve result below mentioned query. make sure set local variables location_name , service_name before executing query:

user.joins(:services).where('users.location_name = ? , services.service_name = ?', location_name ,service_name) 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -