Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails many-to-many existence query

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...

like image 903
danh Avatar asked Mar 30 '12 18:03

danh


1 Answers

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?
like image 140
tadman Avatar answered Sep 30 '22 09:09

tadman