简体   繁体   中英

Preventing instances of this Post model from appearing twice (Rails)?

I have a Post model:

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

a Tag model:

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

and a User model:

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

In the index page users only see posts with tags they have subscribed to:

posts_controller.rb:

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

Now say there is a post with the tags food and drinks , and the user has subscribed to these two tags. He will see the post twice; it seems like it is appearing once as a post tagged as food and then as a post tagged as drinks .

Is there a way of preventing posts like this from appearing twice?

Add :uniq => true as a parameter to the has_many in the User model:

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

The docs at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many-label-Options says:

If true, duplicates will be omitted from the collection. Useful in conjunction with :through.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM