0xSina
0xSina

Reputation: 21553

ActiveRecord query without *_id

I have 3 simple models:

class User < ActiveRecord::Base
    has_many    :subscriptions
end

class Product < ActiveRecord::Base
    has_many    :subscriptions
end

class Subscription < ActiveRecord::Base
    belongs_to  :user
    belongs_to  :product
end

I can do a_subscription.product = a_product and AR knows I mean product_id and everything works fine.

But If i do:

Subscription.where :product => a_product

It throws an error at me Unknown column 'subscriptions.product' - It knows in the first case that I mean product_id but it doesn't in the latter. I am just wondering if this is how it is suppose to be or am I missing something? I can get it to work by saying

Subscription.where :product_id => a_product

by do I have to specify _id?

Upvotes: 0

Views: 63

Answers (2)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14402

I don't think there's an elegant way around that (as of now, see @nash 's answer). However, if you have an instance of a_product and it has has_many on subscriptions, why not just turn it around and say:

subscriptions = a_product.subscriptions

Upvotes: 0

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

Yes, right now you can't pass association to the where method. But you'll be able to do it in Rails 4. Here is a commit with this feature.

Upvotes: 1

Related Questions