0

我正在玩 Acts-As-Taggable Rails gem。我收到以下消息,因为我相信标签模型正在寻找不存在的“post_id”(而不是帖子模型/表中的“id”)。

我是否需要修改模型或控制器才能使其正常工作?

当我尝试显示帖子时发生错误。

更新: - 该错误似乎是由帖子视图(show.html.erb)引起的。帖子视图是指帖子模型(tag_list)。

错误:

 Mysql2::Error: Unknown column 'taggings.post_id' in 'where clause': SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`post_id` = 4

后控制器(显示);

def show
  @post = Post.find(params[:id])

 respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @post }
   end
 end

发布 show.html.erb:

<%= form_for(@post) do |post_form| %>
..
<div class="field">
  <%= post_form.label :tag_list, "Tags (separated by commas)" %><br />
  <%= post_form.text_field :tag_list %>
</div>

岗位型号:

class Post < ActiveRecord::Base
  attr_accessible :content, :name, :title, :tag_list #:tags_attributes

  has_many :taggings
  has_many :tags, through: :taggings

  def self.tagged_with(name)
Tag.find_by_name!(name).posts
  end

  def self.tag_counts
    Tag.select("tags.*, count(taggings.tag_id) as count").
        joins(:taggings).group("taggings.tag_id")
  end

  def tag_list
    tags.map(&:name).join(", ")
  end

 def tag_list=(names)
    self.tags = names.split(",").map do |n|
      Tag.where(name: n.strip).first_or_create!
    end
  end

#Validations
  validates :name,  :presence => true
  validates :title, :presence => true,
        :length => { :minimum => 5 }

  has_many :comments, :dependent => :destroy

#  accepts_nested_attributes_for :tags, :allow_destroy => :true,
#                                :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end

标签型号:

class Tag < ActiveRecord::Base
 belongs_to :post
 has_many :taggings
 has_many :posts, through: :taggings
end

标记模型:

class Tagging < ActiveRecord::Base
 belongs_to :tag
belongs_to :post
end
4

1 回答 1

0

经过几个小时的折腾,我终于得到了这个工作。基本上我必须删除所有以前对标签的引用——特别是在 post 控制器和 post 视图中。

然后我按照下面链接描述的步骤安装 Acts-As-Taggable gem。 http://ericlondon.com/tag/acts-as-taggable-on

# add acts as taggable on gem, for tagging (clearly optional)
# edit file: Gemfile
+gem 'acts-as-taggable-on'

# execute bundle to install gems
$ bundle

# create Post model
$ rails generate model Post title:string content:text

# add taggable property to Post model & make mass-assignable
# file: app/models/post.rb
 class Post < ActiveRecord::Base
+  attr_accessible :content, :title, :tag_list
+  acts_as_taggable_on :tags
 end

# run acts as taggable migration
$ rails generate acts_as_taggable_on:migration

# setup database
$ rake db:migrate

我不得不从我的帖子模型中删除名为“名称”的字段,因为这会导致标签模型中的字段名称“名称”发生冲突。

于 2012-10-08T20:00:14.477 回答