[Rails] ActiveRecord Associations
Jarkko Laine
jarkko at jlaine.net
Wed Dec 22 16:11:40 GMT 2004
Eric,
You should have belongs_to :account instead of has_one in your user
class. Belongs_to is supposed to be used in one-to-many relationships
like yours. Take a look at
http://api.rubyonrails.org/classes/ActiveRecord/Associations/
ClassMethods.html
//jarkko
On 22.12.2004, at 17:35, Eric Anderson wrote:
> I have two objects. One is called "Account" the other is called
> "User". The relevant portions of the ActiveRecord objects are:
>
> class User < ActiveRecord::Base
> has_one :account, :foreign_key => 'account'
> end
>
> class Account < ActiveRecord::Base
> has_many :users, :foreign_key => 'account', :dependent => true
> end
>
> In other words, I want to be able to get the current account for a
> given user. And from the account I want to be able to get all of it's
> users. So my SQL is something like:
>
> CREATE TABLE users (
> id INT AUTO_INCREMENT,
> username VARCHAR(20),
> account INT
> )
>
> CREATE TABLE account (
> id INT AUTO_INCREMENT
> )
>
> Now assume that I have a variable called @user which holds a user in
> the database. I now want to get a list of all users that are in the
> same account as @user. My thought is to do something like
>
> @users = @user.account.users.find_all nil, 'username'
>
> This should give me a variable @users which contains all the users
> that are in the same account as @user ordered by username. When I run
> this I get "undefined method `users' for nil:NilClass" which means
> that account is not getting instantiated correctly. And yes the
> particular user record does refer to a valid account record.
>
> What am I missing?
>
> Eric
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Jarkko Laine
http://jlaine.net
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2363 bytes
Desc: not available
Url : http://one.textdrive.com/pipermail/rails/attachments/20041222/f8b77ab1/smime.bin
More information about the Rails
mailing list