防止此Post模型的实例出现两次(Rails)?

时间:2012-03-14 04:23:19

标签: ruby-on-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

在索引页面中,用户只能看到他们订阅了标签的帖子:

posts_controller.rb:

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

现在说有一个标记为fooddrinks的帖子,用户已订阅这两个标记。他会两次看到这个帖子;它看起来像是标记为food的帖子,然后是标记为drinks的帖子。

有没有办法阻止此类帖子出现两次?

1 个答案:

答案 0 :(得分:2)

:uniq => true作为参数添加到has_many模型中的User

has_many :subscribed_posts, :source => :posts, :through => :subscribed_tags, :uniq => true

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many-label-Options处的文档说:

  

:uniq的

     

如果为true,将从集合中省略重复项。有用   结合:通过。