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:
Subscription.where(:user_id => current_user.id, :magazine_id => a_magazine.id).any?
You can also add :through
relationships to check based on a user or the magazine accordingly.
class User < ActiveRecord::Base
has_many :subscriptions
has_many :magazines, :through => :subscriptions
end
This makes testing for matches really easy:
user = User.find(1)
user.magazines.where(:magazine_id => magazine_id).any?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With