Last active
April 16, 2017 00:36
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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