簡體   English   中英

防止此Post模型的實例出現兩次(Rails)?

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

我有一個Post模型:

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的帖子出現。

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

添加:uniq => true作為User模型中has_many的參數:

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,則將從集合中省略重復項。 與以下內容結合使用:通過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM