【发布时间】: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
posts 和 tags 有 many-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