繁体   English   中英

如何使用多个标签过滤页面内容

[英]how can I filter page content using multiple tags

我是Rails的新手,我想使用多个标签过滤页面内容。 我正在使用act_as_taggable_on gem,并设法创建了一个标签云,并根据标签过滤了我的内容。 我使用了以下教程( http://railscasts.com/episodes/382-tagging )。 现在,我无法使用多个tag_types进行过滤。

我在模型/ article.rb中添加了以下代码

actions_as_taggable
actions_as_taggable_on:assetType,:productType

在控制器中,我不知道写多个标签。 我尝试了以下方法

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

  end

在index.html.erb中,我有

<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 %>

在我的_form中

<%= 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>

有人可以帮助我如何修改控制器,索引和_form页面吗? 现在它显示了我所有的帖子,当我单击标签时,内容没有更改

以此作为基本参考点:

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

尝试这个:

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

调整项:

  • 使用空白检查检查每个参数的空字符串和空字符串。 在这种情况下,null和blank可能相同。
  • 将标签添加到数组中,以便我可以一次全部传递它们。 不仅可以简化调用,还可以通过向调用中添加其他参数(例如匹配所有或任何标签)来对匹配样式进行更明确的控制。

希望有帮助,祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM