我添加了gem' act-as-taggable-on' -v 2.3.1在Gemfile中。 Rails版本3.2.13,Ruby -v 1.9.3
在article.rb中,
class Article < ActiveRecord::Base
acts_as_taggable_on :tags
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end
在articles_controller.rb中,
class ArticlesController < ApplicationController
before_filter :authenticate_author!, except: [:index, :show]
def index
myarray = Article.all
@articles = Kaminari.paginate_array(myarray).page(params[:page]).per(10)
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text, :tag_list => [])
end
end
在文章/ _form.html.erb
中<div class="field">
<%= f.label :tag_list, "Tags (separated by commas)" %><br />
<%= f.text_field :tag_list %>
</div>
我在安装了act-on-taggable-gem后运行了以下命令,
rails generate acts_as_taggable_on:migration
rake db:migrate
在articles / index.html.erb
中<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= article.tag_list %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<% if author_signed_in? %>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end%>
</tr>
<% end %>
标签未显示在索引页面中。 但如果我这样做,
article = Article.new(:title => "Awesome")
article.tag_list = "awesome, cool"
article.save
提交事务并在浏览器上显示标记。
为什么标签没有保存并显示在索引页面中?
答案 0 :(得分:0)
标签列表是一个数组,这意味着您需要“循环”以提取数据。每当我使用acts_as_taggable时,我都会通过循环来提取标签。以下内容应该有效:
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td>
<% article.tag_list.each do |tag| %>
<%= tag %>
<% end %>
</td>
<td><%= link_to 'Show', article_path(article) %></td>
<% if author_signed_in? %>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end%>
</tr>
<% end %>