#006 Tags

| 23 minutes | tags 入门
利用一个给Post打tag的例子来讲解has_and_belongs_to_many 和 has_many :through.
db/migrate/20120208105327_create_tags.rb
class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags do |t|
      t.string :name

      t.timestamps
    end
  end
end
db/migrate/20120208111258_create_taggings.rb
class CreateTaggings < ActiveRecord::Migration
  def change
    create_table :taggings do |t|
      t.integer :post_id
      t.integer :tag_id

      t.timestamps
    end
  end
end
app/models/tagging.rb
class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :post
end
app/models/tag.rb
class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, :through => :taggings
end
app/models/post.rb
class Post < ActiveRecord::Base

  has_many :taggings
  has_many :tags, :through => :taggings

  scope :tag_with, lambda{|tag_name| joins(:tags).where("tags.name = ?", tag_name)}
  scope :latter_than, lambda{|time| joins(:taggings).where("taggings.created_at > ?", time)}

  # Post.tag_with("yujie")

  #def self.tag_with(tag_name)
  #  Tag.find_by_name(tag_name).try(:posts)
  #end
end
Similar Episodes