Rails User model has_many activities (observer) but should also be observed
I'm running into an issue with an existing ActiveRecord::Observer
model that records various Activities
of a User
the site. Everything was working really well, until I tried to observe
the User
class with the same Activity
model that it uses to observe
other mo开发者_运维百科dels. Consider that:
class Activity < ActiveRecord::Base
belongs_to :user
belongs_to :item, :polymorphic => true
end
class ActivityObserver < ActiveRecord::Observer
observe :billing, :call, :vanity_number
end
class User < ActiveRecord::Base
has_many :comments
has_many :activities
end
class Comment < ActiveRecord::Base
belongs_to :user
has_many :activities, :as => :item
end
The above worked fine. A query for User.activities
would return rows of Comment
Activities
. As soon as I added :user
to the observe
method in ActivityObserver
and changed has_many :activities
in the User
model to has_many :activities, :as => :item
, User.activities
would only return rows that were activities pertaining to that User
instance and not any Comments
Why is this? What can I do to get this working as expected?
When you changed
class User < ActiveRecord::Base
has_many :activities
end
to
class User < ActiveRecord::Base
has_many :activities, :as => :item
end
it is now looking at the item_id
field in the activities table where the type field is User to pull back activities where item_id = users.id
. Before it was looking at the user_id
field in activities. Since the item_id
field and type field cannot have two values, you made it so that an activity points at either a user or a comment. It can't be both.
精彩评论