Forum: Ruby on Rails Re: Some advice on DB modeling

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A79568f589e81bcd45837f2be2eb4260?d=identicon&s=25 Frank Spychalski (Guest)
on 2006-01-06 11:02
(Received via mailing list)
I have more or less the same problem. I'm trying to build a system where
users can enter their friends. But the solutions seems not to work for
me.

I used same sql:

CREATE TABLE `friends` (
    `user_id` int(11) NOT NULL default '0',
    `friend_id` int(11) NOT NULL default '0',
    KEY `user_id` (`user_id`),
    KEY `friend_id` (`friend_id`),
    CONSTRAINT `friends_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES
`users`  (`id`),
    CONSTRAINT `friends_ibfk_2` FOREIGN KEY (`friend_id`) REFERENCES
`users` (`id`)
)

My user.rb looks like this:

class User < ActiveRecord::Base
    has_and_belongs_to_many :friends, :join_table => 'friends',
:class_name => 'User', :foreign_key => 'friend_id'

   has_and_belongs_to_many :friends_of, :join_table => 'friends',
:class_name => 'User', :foreign_key => 'user_id',
:association_foreign_key => 'friend_id'

   attr_accessor :new_password
   attr_accessor :friends
   attr_accessor :friends_of

...
end

But when I use user.friends or user.friends_of they always return nil
even after I entered some data in the db manually. There are no errors
in the logfile...

Any ideas?

thanks
Frank
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-01-07 06:41
(Received via mailing list)
On 1/6/06, Frank Spychalski <rails-ml@spychalski.de> wrote:
>     CONSTRAINT `friends_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES
>
>
> But when I use user.friends or user.friends_of they always return nil
> even after I entered some data in the db manually. There are no errors
> in the logfile...
>
> Any ideas?
>
You don't need attr_accessors for associations.  has_many :whatevers
creates the 'whatevers' method for you.

P.S. You can do multiple attr_accessors on one line, separated with
commas, if you want.
e.g. attr_accessor :thing1, :thing2, :thing3
A79568f589e81bcd45837f2be2eb4260?d=identicon&s=25 Frank Spychalski (Guest)
on 2006-01-08 21:08
(Received via mailing list)
Wilson Bilkovich wrote:
>
> You don't need attr_accessors for associations.  has_many :whatevers
> creates the 'whatevers' method for you.
>
> P.S. You can do multiple attr_accessors on one line, separated with
> commas, if you want.
> e.g. attr_accessor :thing1, :thing2, :thing3

thanks - the accessors where leftovers from a previous try and I forgot
to remove them...

Frank
This topic is locked and can not be replied to.