2012-03-14 33 views
0

我有一個型號:防止此Post模型的實例出現兩次(Rails)?

class Post < ActiveRecord::Base  
    belongs_to :user 

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

    attr_writer :tag_names 
    after_save :assign_tags 
    before_create :init_sort_column 

    def tag_names 
    @tag_names || tags.map(&:name).join(" ") 
    end 

    private 

    def assign_tags 
    self.tags = [] 
    return if @tag_names.blank? 
    @tag_names.split(" ").each do |name| 
     tag = Tag.find_or_create_by_name(name) 
     self.tags << tag unless tags.include?(tag) 
    end 
    end 
end 

一個標籤型號:

class Tag < ActiveRecord::Base 
    has_many :taggings, :dependent => :destroy 
    has_many :posts, :through => :taggings 
    has_many :subscriptions 
    #has_many :subscribed_users, :source => :user, :through => :subscriptions 
end 

用戶型號:

class User < ActiveRecord::Base 
    (Code related to Devise) 

    has_many :posts, :dependent => :destroy 
    has_many :subscriptions 
    has_many :subscribed_tags, :source => :tag, :through => :subscriptions 
    has_many :subscribed_posts, :source => :posts, :through => :subscribed_tags 

    attr_writer :subscribed_tag_names 
    after_save :assign_subscribed_tags 

    def subscribed_tag_names 
    @subscribed_tag_names || subscribed_tags.map(&:name).join(' ') 
    end 

    private 

    def assign_subscribed_tags 
    #self.subscribed_tags = [] 
    return if @subscribed_tag_names.blank? 
    @subscribed_tag_names.split(" ").each do |name| 
     subscribed_tag = Tag.find_or_create_by_name(name) 
     self.subscribed_tags << subscribed_tag unless subscribed_tags.include?(subscribed_tag) 
    end 
    end 
end 

在索引頁面的用戶只查看包含訂閱標籤的帖子d到:

posts_controller.rb:

@posts = current_user.subscribed_posts.paginate(:page => params[:page], 
               :per_page => 5, 
               :order => params[:order_by]) 

說現在有一個與標籤fooddrinks後,用戶已經訂閱了這兩個標籤。他會看到這個帖子兩次;它好像是作爲標記爲food的帖子出現一次,然後作爲標記爲drinks的帖子出現。

有沒有辦法阻止這樣的帖子出現兩次?

回答