I have 2 models: User
and PrivateMessage
which must be associated (as user has many private messages as reciever and sender, private messages belongs to user)
我有两个模型:User和PrivateMessage必须关联(因为用户有许多私有消息作为reciever和sender,私有消息属于用户)
It's my private_messages
table structure:
它是我的private_messages表结构:
private_messages:
sender_id:integer
reciever_id:integer
title:string
message:text
It's hard for me to understand how can I connect same message for both sender user and reciever user, now my models code looks like:
我很难理解如何为发送者用户和接收者用户连接相同的消息,现在我的模型代码如下:
class User < ActiveRecord:Base
has_many :private_messages
end
and
和
class PrivateMessage < ActiveRecord::Base
belongs_to :user, :through => :sender_id
belongs_to :user, :through => :reciever_id
end
Is that correct?
那是正确的吗?
1 个解决方案
#1
6
You have to rename your associations to tell them apart:
你必须重命名你的联系,以区分它们:
class PrivateMessage < ActiveRecord::Base
belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id'
end
class User < ActiveRecord::Base
has_many :sent_messages, :class_name => 'PrivateMessage', :foreign_key => 'sender_id', :dependent => :destroy
has_many :received_messages, :class_name => 'PrivateMessage', :foreign_key => 'receiver_id', :dependent => :destroy
end
#1
6
You have to rename your associations to tell them apart:
你必须重命名你的联系,以区分它们:
class PrivateMessage < ActiveRecord::Base
belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id'
end
class User < ActiveRecord::Base
has_many :sent_messages, :class_name => 'PrivateMessage', :foreign_key => 'sender_id', :dependent => :destroy
has_many :received_messages, :class_name => 'PrivateMessage', :foreign_key => 'receiver_id', :dependent => :destroy
end