1

I have a Log model with a polymorphic association and another association to a User model:

class Log < ActiveRecord::Base
  belongs_to :loggable, polymorphic: true
  belongs_to :user
end

In my User model, I have a has_many association to the Log model:

class User < ActiveRecord::Base
  has_many :logs
end

I want to have another association in the User model as follows:

class User < ActiveRecord::Base
  has_many :logs
  has_many :logs, as: :loggable
end

But I imagine that those two associations will conflict each other (I don't know, didn't try)...

So is that the right approach to this problem? Or there is a better way of doing it?

4
  • Why you need another association to Log? Aug 26, 2013 at 14:20
  • I need one association where User is the "actor" and one where User is the "subject". For example: "user1 added a note on contact2" (user1 is the actor) and user2 suspended user1 (user1 is the subject, user2 is the actor) Aug 26, 2013 at 14:23
  • You're only logging users or other models as well? Can't you do this on Logs table (actor_id, subject_id), use and make scopes on the User model? Aug 26, 2013 at 14:26
  • 1
    I'm logging multiple models. @Marek Lipka gave the right solutions, where the Log model stays as generic as possible. Aug 26, 2013 at 14:29

1 Answer 1

3

How about renaming one of your associations like this:

class User < ActiveRecord::Base
  has_many :user_logs, class_name: 'Log'
  has_many :logs, as: :loggable
end

To fetch all your logs associated with given user, you could set scope on Log model like this:

class Log < ActiveRecord::Base
  belongs_to :loggable, polymorphic: true
  belongs_to :user

  scope :for_user, lambda { |user|
    where('user_id = :user_id OR (loggable_type = "User" AND loggable_id = :user_id)', user_id: user.id)
  }
end
2
  • That's a good idea that I didn't think of, but I would like to get all the logs associated with a User with one command (sorted correctly), if it's possible of course. So if there is a way to name the two associations the same way it would be ideal. Otherwise, I'll gladly accept your answer. Aug 26, 2013 at 14:11
  • @AzizLight I edited my answer. I think it's the best way to handle your problem. Aug 26, 2013 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.