Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the recommended way to add custom scopes and other stuff to the Activity model? #219

Closed
oboxodo opened this issue May 15, 2015 · 3 comments

Comments

@oboxodo
Copy link

oboxodo commented May 15, 2015

It's not clear to me from the documentation and just trying to re-open the class is proving difficult because of its "special" inheriting scheme (I assume).

I'm needing to add specific belongs_to relationships per trackable type to be able to do some deep joins. I'm using this "hack" to do joins on polymorphic relationships which works pretty well.

So from what I see in the wiki here, I assume your recommendation would be to create an app/models/activity.rb file and do something like:

PublicActivity::Activity.class_eval do
  # These are hacks to be able to use `joins` on the `trackable` polymorphic association.
  # Based on: http://stackoverflow.com/a/16124295
  belongs_to :post, -> { where(activities: { trackable_type: "Post" }) }, foreign_key: "trackable_id"
  belongs_to :comment, -> { where(activities: { trackable_type: "Comment" }) }, foreign_key: "trackable_id"
  belongs_to :project, -> { where(activities: { trackable_type: "Project" }) }, foreign_key: "trackable_id"

  scope :by, -> (user) { where(owner: user) }

  def self.most_recent
    order(:updated_at).last
  end
end

Can you confirm this is the best/expected way to do it or can you suggest a more "official" way?

@pokonski
Copy link
Member

@oboxodo yeah this is the solution that worked for everyone. Inheriting is not recommended as your class won't be used by P_A.

@klappradla
Copy link

I use a similar approach to be able to eager load different associations for different types of trackables in one query:

PublicActivity::Activity.class_eval do
  belongs_to :post, -> { includes(:activities).where(activities: { trackable_type: 'Post' }) }, foreign_key: :trackable_id
  belongs_to :meeting, -> { includes(:activities).where(activities: { trackable_type: 'Meeting' }) }, foreign_key: :trackable_id
end

But, @oboxodo , stuff like that for me only works when putting the code into config/initializers/public_activity.rb. Does it truly work with a model file for you?

@CEB-21
Copy link

CEB-21 commented Nov 26, 2015

@klappradla Same here. I can can also confirm this only worked for me when this file is in config/initializers/public_activity.rb.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants