如何“订阅”用户到此Tag模型的现有实例而不是创建新的?

时间:2012-03-03 06:44:59

标签: ruby-on-rails

我有一个发布模型:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :tag_names

  belongs_to :user

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

  attr_writer :tag_names
  after_save :assign_tags

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

  private

  def assign_tags
    if @tag_names
      self.tags = @tag_names.split(" ").map do |name|
        Tag.find_or_create_by_name(name)
      end
    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
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :avatar

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

帖子标记具有多对多关系(以下是联接表的模型):

class Tagging < ActiveRecord::Base
  belongs_to :post  
  belongs_to :tag
end

用户标记还具有多对多关系:

class Subscription < ActiveRecord::Base
  belongs_to :user  
  belongs_to :tag
end

只有具有用户订阅的标签的帖子才会显示:

  def index
    @title = "Posts"
    @posts = current_user.subscribed_tags.map(&:posts).flatten.paginate(:page => params[:page], :per_page => 5)

假设我为帖子创建了一个标签:

$ post.tags.create(:name => "food")
$ post.tags
=> [#<Tag id: 6, name: "food", created_at: "2012-03-02 10:03:59", updated_at: "2012-03-02 10:03:59"] 

现在我不知道如何订阅用户到该标签。

我试过了:

$ user.subscribed_tags.create(:name => "food")
$ post.tags
=> [#<Tag id: 7, name: "food", created_at: "2012-03-02 10:04:38", updated_at: "2012-03-02 10:04:38"] 

但正如您所看到的那样,它实际上会创建一个新标记,而不是将带有ID 6的食品标记添加到user.subscribed_tags属性。

有任何解决此问题的建议吗?

1 个答案:

答案 0 :(得分:2)

您可以像添加数组一样附加到用户的subscriped_tags。

ex:user.subscribed_tags << Tag.find_by_name("food")