簡體   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