Monday, 15 September 2014

ruby on rails - ActiveRecord has_and_belongs_to_many: find models with all given elements -



ruby on rails - ActiveRecord has_and_belongs_to_many: find models with all given elements -

i'm implementing search scheme uses name, tags, , location. there has_and_belongs_to_many relationship between server , tag. here's search method looks like:

def self.search(params) @servers = server.all if params[:name] @servers = @servers.where "name ilike ?", "%#{params[:name]}%" end if params[:tags] @tags = tag.find params[:tags].split(",") # how eliminate servers not have these tags? end # todo: eliminate not have location specified in params. end

the tags parameter comma-separated list of ids. question stated in comment in if params[:tags] conditional block. how can eliminate servers not have tags specified?

bonus question: way speed up? fields optional, , using postgres exclusively.

edit

i found way this, have reason believe extremely slow run. there way that's faster i've done? perhaps way create database work?

tags = tag.find tokens servers = servers.reject |server| missing_a_tag = false tags.each |tag| if server.tags.find_by_id(tag.id).nil? missing_a_tag = true end end missing_a_tag end

retrieve servers given tags with

if params[:tags] tags_ids = params[:tags].split(',') @tags = tag.find(tags_ids) @servers = @servers.joins(:tags).where(tags: {id: tags_ids}).group('servers.id').having("count(*) = #{tags_ids.count}") end

the group(...).having(...) part selects servers all requested tags. if you're looking servers have at least 1 of tags, remove it.

with solution, search done in single sql request, improve solution.

ruby-on-rails postgresql activerecord

No comments:

Post a Comment