Model wiadomości

Witam,

Mam problem z utworzeniem modelu wiadomości. Wiadomość w bazie danych to rekord, który ma dwa klucze zewnętrzne user_id i friend_id, z tym, że oba zawierają id użytkownika, ale user_id do właściciela wiadomości, a friend_id do osoby, która wysłała lub do której była wiadomości.

Chciałem, żeby dało się zrobić coś takiego w widoku: message.user.login i message.friend.login, czy da się to jakoś ładnie rozwiązać tak, żebym nie musiał pisać metody friend w modelu?

Migracja dla wiadomości

[code]class CreateMessages < ActiveRecord::Migration
def self.up
create_table :messages, :force => true do |t|
t.integer :user_id
t.integer :friend_id
t.string :title
t.text :message
t.boolean :read

  t.timestamps
end

end

def self.down
drop_table :messages
end
end[/code]
Aktualny model

[code]class Message < ActiveRecord::Base

belongs_to :user, :foreign_key => ‘user_id’
belongs_to :user, :foreign_key => ‘friend_id’

def friend
User.find(friend_id)
end
end[/code]
Pozdrawiam

Masz błąd w asocjacjach modelu. Zamiast pisać dwa razy ‘belongs_to :user’ napisz:

[code=ruby]class Message < ActiveRecord::Base

belongs_to :user
belongs_to :friend, :class_name => “User”, :foreign_key => “friend_id”

end[/code]
W razie dalszych problemów, polecam zajrzeć do dokumentacji.

[quote=GhandaL]Masz błąd w asocjacjach modelu. Zamiast pisać dwa razy ‘belongs_to :user’ napisz:

[code=ruby]class Message < ActiveRecord::Base

belongs_to :user
belongs_to :friend, :class_name => “User”, :foreign_key => “friend_id”

end[/code]
W razie dalszych problemów, polecam zajrzeć do dokumentacji.[/quote]
Dzięki wielkie!