rails/ruby: filtering
query = Micropost.order("created_at desc")
unless params[:tag_id].blank? or params[:tag_id] == "Select a tag"
tags = Tag.all
params[:tag_id].each do |index|
query = tags[Integer(index) - 1].microposts.order("created_at desc") & query
end
end
This is the code I have. Basically tags have microposts and when I specify an array of tags from params[:tag_id] (I use a multiple select_tag), I want the intersection of all those microposts specified by the tags.
This code works when the array has only one tag but d开发者_Python百科oesnt seem to work with more than 1. Wheres the bug?
I'm not sure if I fully understand what you are trying to do. But perhaps something along these lines is what you are after (goes inside the unless
)?
For posts that have any tag:
tags = Tags.where(:id => params[:tag_id]).all
posts_with_tags = tags.map(&:microposts).flatten.uniq
For posts that have all tags:
tags = Tags.where(:id => params[:tag_id]).all
posts_with_tags = tags.map(&:microposts).inject { |memo, elem| memo & elem }
if you want the intersection of all Micropost with the collection of microposts associated with the tags selected you have only to query for all the micropost associated with the selected Tag and collect the microposts. with rails3
unless params[:tag_id].blank? or params[:tag_id] == "Select a tag"
query= Tag.where(["id in (?)",params[:tag_id]]).collect(&:microposts).uniq
end
maybe i have misunderstood your question , sorry .
精彩评论