Question

I have a Many to Many association with Users and Tags. I want to show users based on the tag checkboxes that are selected. Here is my search form in the view.

<%= form_tag users_path, :method => 'get' do %>
    <% @tags.each do |tags| %>
      <li><%= check_box_tag "tag_id[]", tags.id %>
          <%= tags.name %>
      </li>
    <% end %>
    <%= submit_tag "Search" %>

  <% end %>

When I click a couple boxes, it stores those in the "tag_id". My params looks like this:

 params
=> {"utf8"=>"✓",
 "tag_id"=>["1", "3"],
 "commit"=>"Search",
 "action"=>"index",
 "controller"=>"users"}

I cannot for the life of me figure out how to search in the controller. I need something like this:

def index
#psuedo code -- if searching#
 @users = User.all.where(#all users that have the selected tag_id's associated with the User. In this example, all users with tag_id's 1 and 3)
else
 @tags = Tag.all
 @users = User.all

end

my pitiful attempts:

def index
 binding.pry
 @tags = Tag.all
 @users = User.all.where(self.tags)
 #@users = User.search(params[:search])
end
Was it helpful?

Solution

My answer may require you to change quite a bit of stuff, but why struggle with this when there is a Gem you can use to do most, if not all, of what you are trying to do? Here's a Rails Cast: http://railscasts.com/episodes/382-tagging?view=asciicast

Use this Gem: Acts-as-taggable-on

https://github.com/mbleigh/acts-as-taggable-on

The only thing I haven't figured out yet is multiple tags but this should work for you.

OTHER TIPS

Your view is fine I think :) Try that :

def index
  @users = User.all(joins: :tags, conditions: {tags: {id: params.slice(:tag_id)}})
end

def index
  @users = User.includes(:tags).where('tags.id IN ?', params[:tag_id])
end

If the first one does not work, the second one should u_u, but I was quite sure of the first one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top