views:

41

answers:

2

I have the following:

class User < ActiveRecord::Base
 has_one :subscription
end
class Subscription < ActiveRecord::Base
 belongs_to :user
end

The User has a subscription_id and thus can have only one subscription (which is what I want).

Which works fine, but now I do:

@users = User.find(:all)

and I want all the subscriptions to be included.

I tried:

@users = User.find(:all, :include=>[:subscription]) # include subscription

But that would like the subscription table to have a user_id (SQLite3::SQLException: no such column: subscriptions.user_id: SELECT "subscriptions".* FROM "subscriptions" WHERE ("subscriptions".user_id = 2)).

Which is (ofcourse) not what I want.

I am new at RoR and I couldn't find a good example of this case in the books I have nor on the web.

+1  A: 

First of all if the user has foreign key (subscription_id) then it should have belongs_to not the other way around. As the Rails docs says for has_one method:

"This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use belongs_to instead"

(taken from: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834)

Second, in your example you tried to find User and include user. You need to do this:

@users = User.find(:all, :include=>[:subscription])
Slobodan Kovacevic
In case I wasn't clear... User needs to have belongs_to :subscription and Subscription needs to have has_many :users
Slobodan Kovacevic
Jikes. Reading is difficult... Thanks, works now.
CharlesS
+4  A: 

I think you have your associations the wrong way round on the model objects. You should have

class User < ActiveRecord::Base
  belongs_to :subscription
end
class Subscription < ActiveRecord::Base
  has_one :user
end

belongs_to should be used on the side of the association that defines the foreign key (in this case subscription_id). Semantically this probably looks a bit odd, but that's because in this case rails would kind of expect a user_id to be on the subscriptions table instead of the other way round as you have it.

After that

User.find(:all, :include=>[:subscription]) 

Should work fine

Ceilingfish
Thanks, works now.
CharlesS