У меня есть Пост Модель:
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
a Tag модель:
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
.
Есть предложения по решению этой проблемы?