【问题标题】:How to 'subscribe' an user to an existing instance of this Tag model instead of creating a new one?如何“订阅”用户到此标签模型的现有实例,而不是创建一个新实例?
【发布时间】:2012-03-03 15:21:31
【问题描述】:

我有一个 Post 模型:

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

poststagsmany-to-many 关系(以下是连接表的模型):

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 属性中。

有解决这个问题的建议吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你可以追加到用户的 subscriped_tags,就像你做一个数组一样。

    例如:user.subscribed_tags &lt;&lt; Tag.find_by_name("food")

    【讨论】:

    • 嘿,我刚巧在一秒钟前意识到这一点。无论如何,谢谢!
    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多