ruby-on-railsrubyacts-as-taggable-ontag-cloudacts-as-taggable

how can I filter page content using multiple tags


I am newbie in rails and I want to filter my page content using muptiple tags. I am using act_as_taggable_on gem and I managed to have a tag-cloud and filter my content according tags. I used the following tutorial (http://railscasts.com/episodes/382-tagging). Now I couldn't manage to filter using multiple tag_types.

I added in my model/ article.rb the following code

acts_as_taggable
acts_as_taggable_on :assetType, :productType

in controller I don't know to write multiple tags . I tried the following way

def index
  if (params[:assetType] and params[:productType])
   @articles = Article.tagged_with(params[:assetType]).tagged_with(params[:productType])
  else
      @articles = Article.all
    end

  end

In my view in index.html.erb I have

<div id="tag_cloud">
  <% tag_cloud Article.productType_counts, %w[s m l] do |tag, css_class| %>
    <%= link_to tag.name, tag_path(tag.name), class: css_class %>
  <% end %>
</div>
<div id="tag_cloud_asset">
  <% tag_cloud Article.assetType_counts, %w[s m l] do |tag, css_class| %>
    <%= link_to tag.name, tag_path(tag.name), class: css_class %>
  <% end %>
</div>
<div class="article-content">  
  <% @articles.each do |article| %>    
      <h3><%= article.title %></h3>
      <p><%= article.content %></p>  

  <% end %>

and in my _form I have

<%= form_for(@article) do |f| %>
    <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="field">
    <%= f.label :assetType_list, "Tags (Asset Type separated by commas)" %><br />
    <%= f.text_field :assetType_list %>
    <%= f.label :productType_list, "Tags (Product Type separated by commas)" %><br />
    <%= f.text_field :productType_list %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>

Could someone help me how should I modilfy my controller, index and _form page? now it is showing all my posts and when I click on tags the content is not changed


Solution

  • Using this as a basic reference point:

    https://github.com/mbleigh/acts-as-taggable-on#finding-tagged-objects

    Try this:

    def index
      tags = []
      tags << params[:assetType] unless params[:assetType].blank?
      tags << params[:productType] unless params[:productType].blank?
    
      if tags.count == 2
        @articles = Article.tagged_with(tags)
      else
        @articles = Article.all
      end
    end
    

    Adjustments:

    Hope that helps, good luck!