Skip to content

Instantly share code, notes, and snippets.

@esteedqueen
Last active April 16, 2017 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esteedqueen/d98649eb799e1b38e4c1ac38592700cf to your computer and use it in GitHub Desktop.
Save esteedqueen/d98649eb799e1b38e4c1ac38592700cf to your computer and use it in GitHub Desktop.
TIL - add scope for has_many relationships by the model's specific attribute(s); not just by the standard rails model_id attribute
# add scope (with one or more attributes) for has_many relationships
# This is great for polyphomism when you want different models to be able to have subscriptions; so that you don't just attach only one model to subscriptions
# Reference: http://edgeguides.rubyonrails.org/association_basics.html#scopes-for-has-many
class Question < ActiveRecord::Base
has_many :subscriptions, -> { where "type = 'Question'" }, :foreign_key => "subscribed_item_id"
end
class Subscription < ActiveRecord::Base
# attributes: type, subscribed_item_id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment