Kind of a ruby-noob active record query question:
Magazine
has_many :subscriptions
User
has_many :subscriptions
Subscription
belongs_to :user
belongs_to :magazine
In a controller, I’d like to efficiently ask if current_user subscribes to a_magazine. I think it should be something like the following…
Subscription.where("user_id = ? and magazine_id = ?", current_user.id, a_magazine.id).count > 0
a) looks right? b) is there a more efficient way (assuming indexes on the FKs) c) stylistically, is there a more accepted or concise way?
Thanks in advance…
The more concise way to do it involves using the hash method of declaring queries which reads more easily and leaves fewer opportunities for mistakes:
You can also add
:throughrelationships to check based on a user or the magazine accordingly.This makes testing for matches really easy: