Acts as tagable on

提供: sha.ngri.la
2016年3月5日 (土) 05:23時点におけるTara.ttm (トーク | 投稿記録)による版 (def createとdef updateを、編集)
移動先: 案内検索

インストール

Gemfileに追加

gem 'acts-as-taggable-on'

インストール

> bundle install
(中略)
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
Post-install message from acts-as-taggable-on:
When upgrading

Re-run the migrations generator

    rake acts_as_taggable_on_engine:install:migrations

It will create any new migrations and skip existing ones


##Breaking changes:

  - ActsAsTaggableOn::Tag is not extend with ActsAsTaggableOn::Utils anymore.
    Please use ActsAsTaggableOn::Utils instead

書かれているとおりにする。

> rake acts_as_taggable_on_engine:install:migrations
(中略)
> rake db:migrate

設定

この例では、imageモデルに適用しているので、/app/models/images.rbacts_as_taggableを追加。

class Image < ActiveRecord::Base
	acts_as_taggable
end

コントローラーを編集

/app/controllers/images_controller.rbを編集します。

def indexを編集

編集前

  def index
    @images = Image.all
  end

編集後

  def index
    @tags = Image.tag_counts
    if params[:tag].present?
      @images = Image.tagged_with(params[:tag]).order('id DESC').page(params[:page]).per(10)
    else
      @images = Image.order('id DESC').page(params[:page]).per(10)
    end
  end

.page(params[:page]).per(10)の部分は、kaminari使ってるので、その設定も入ってます。

def createとdef updateを、編集

def createと、def update@image.tag_list = params[:image][:tag_list]を追加。

def create
  @image.tag_list = params[:image][:tag_list]
(中略)

def update
  @image.tag_list = params[:image][:tag_list]
(中略)

def image_params
    params.require(:image).permit(:memo, :title, :imgurl, :tag_list)

タグを表示する

index.html.erbになら、@imagesimageはモデル名で変わります。

    <% @images.each do |image| %>
(中略)
          <% image.tags.each do |tag| %>
            <%= link_to(tag.name, images_path(tag: tag.name)) %>
          <% end %><br>

show.html.erbには、

  <% @image.tags.each do |tag| %>
    <%= link_to tag.name, images_path(tag: tag.name) %>
  <% end %>

_form.html.erbには、

  <div class="field">
    <%= f.label :tag_list %><br>
    <%= f.text_field :tag_list %>
  </div>

を追加します。

タグクラウド

表示させるテンプレートに追加。ImageというモデルなのでImageimagesは環境に合わせて変更する必要があります。

<div id="tag_cloud">
  <% tag_cloud Image.tag_counts, %w{s m l} do |tag, css_class| %>
    <%= link_to tag.name, images_path(tag: tag.name), class: css_class %>
  <% end %>
</div>

images.css.scssファイルにタグクラウド用の記載を追加。

#tag_cloud {
  width: 100%;
  line-height: 1.6em;
  .s { font-size: 0.8em; }
  .m { font-size: 1.2em; }
  .l { font-size: 1.8em; }
}

複数のタグを指定してオブジェクトを取得する

標準

items = Item.find_tagged_with("テント, タープ")
# => 「テント」もしくは「タープ」のいずれかのタグを持つレコードを取得

AND検索するには、optionで、:match_all => trueを指定する。

items = Item.find_tagged_with("テント, 本体", :match_all => true)
# => 「テント」でかつ「本体」両方のタグを持つレコードを取得

Link