Forum: Ruby on Rails Models relations definition

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.
CiriusMex (Guest)
on 2009-04-01 08:32
(Received via mailing list)
Hi, got an issue here ^^ Ok so my problem is that I have a table named
"users_accounts" and another one named "accounts_messages". As you
will guess, accounts_messages is a list of messages that
"users_accounts" can interchange. Here comes my problem:
for each message I need to know who is the autor and the destinator,
so in "accounts_messages" I have two parameters which are:
autor_user_account_id (refers to the autor account) and
user_account_id (refers to the destinator account).

So in my AccountMessage ruby model class I want to refer two times to
the users_accounts table. How do I do that? More precisely my question
is how do I do to keep the relation navigability for the two
parameters? If I declare those two lines:
class AccountMessage < ActiveRecord::Base
    belongs_to :autor_user_account
    belongs_to :user_account

    ...
end

obviously autor_user_account wont refer alone to the UserAccount
class. So how can I declare those two parameters in order to use them
that way for exemple:

message = AccountMessage.find(...)
printf "autor name: #{message.autor_user_account.name}"
printf "destinator name: #{message.user_account.name}"

We supose here that the "users_accounts" table has a name property of
course.

Hope it's understandable :)
Olivier.
Philip H. (Guest)
on 2009-04-01 09:26
(Received via mailing list)
> the users_accounts table. How do I do that? More precisely my question
> is how do I do to keep the relation navigability for the two
> parameters? If I declare those two lines:
> class AccountMessage < ActiveRecord::Base
>    belongs_to :autor_user_account
>    belongs_to :user_account
>
>    ...
> end
>>

Look into the :class_name and :foreign_key parameters that go along
with belongs_to/has_one/has_many.

:class_name
     Specify the class name of the association. Use it only if that
name can‘t be inferred from the association name. So has_one :author
will by default be linked to the Author class, but if the real class
name is Person, you‘ll have to specify it with this option.

:foreign_key
     Specify the foreign key used for the association. By default this
is guessed to be the name of the association with an "_id" suffix. So
a class that defines a belongs_to :person association will use
"person_id" as the default :foreign_key. Similarly,
belongs_to :favorite_person, :class_name => "Person" will use a
foreign key of "favorite_person_id".
CiriusMex (Guest)
on 2009-04-01 12:11
(Received via mailing list)
Great, thank you very mucho for the help! ^^
This topic is locked and can not be replied to.