我試圖實現以下,關係和對象調用軌道4的has_many通過 - 消息發送者接收與
用戶可以發送許多消息(user.sent_messages) 一個消息可以具有一個發送器(消息。發送者)
用戶可以接收許多消息(user.received_messages) 一個消息可以具有許多接收器(message.receivers)
我的模式是這樣的:
create_table "activities", force: true do |t|
t.integer "sender_id"
t.integer "message_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "receiver_id"
end
create_table "messages", force: true do |t|
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "read", default: false
end
個
我的模型是這樣的:
class User < ActiveRecord::Base
has_many :activities, class_name: 'Activity', foreign_key: 'sender_id', dependent: :destroy
has_many :sent_messages, through: :activities
has_many :reverse_activities, class_name: 'Activity', foreign_key: 'receiver_id'
has_many :received_messages, through: :reverse_activities
end
class Activity < ActiveRecord::Base
belongs_to :sent_messages, class_name: 'User'
belongs_to :received_messages, class_name: 'User'
belongs_to :message
end
class Message < ActiveRecord::Base
has_many :activities, foreign_key: 'sender_id'
has_one :sender, through: :activities, foreign_key: 'sender_id', class_name: 'User'
has_many :reverse_activities, foreign_key: 'receiver_id', class_name: 'User'
has_many :receivers, through: :reverse_activities, source: :receiver
end
方法sent_messages & received_messages工作,但是它們指向直接返回給用戶表並返回該用戶,而不是信息的細節。
我還沒有試圖讓消息模型工作,因爲用戶模型是不正確的。
謝謝!
由於這兩個建議,我已經得到了以下工作
class User < ActiveRecord::Base
has_many :activities, class_name: 'Activity', foreign_key: 'sender_id'
has_many :sent_messages, through: :activities, foreign_key: 'message_id', class_name: 'Message', source: :sender
has_many :reverse_activities, class_name: 'Activity', foreign_key: 'receiver_id'
has_many :received_messages, through: :reverse_activities, foreign_key: 'message_id', class_name: 'Message', source: :receiver
end
class Message < ActiveRecord::Base
has_one :sent_activities, class_name: 'Activity', foreign_key: 'message_id'
has_one :sender, through: :sent_activities, foreign_key: 'sender_id', class_name: 'User'
has_many :receiver_activities, class_name: 'Activity', foreign_key: 'message_id'
has_many :receivers, through: :receiver_activities, foreign_key: 'receiver_id', class_name: 'User'
validates :body, presence: true
end
class Activity < ActiveRecord::Base
belongs_to :sender, class_name: 'User'
belongs_to :receiver, class_name: 'User'
belongs_to :receiver, class_name: 'Message'
belongs_to :sender, class_name: 'Message'
end
根據需要方法的我正在努力的結果。
現在只是爲了讓創建操作工作!
嗨Rich,感謝你的看法,除此之外,這一切都會使我受限於a)一條消息只能發送給一個人,或者b)不得不復制整個消息內容,併發送給多個人。這是我想用我的活動連接表抽象出來的。 – benlaplanche
哦,我以前只是想要單個收件人/發件人?我可以重構包括一個連接表,如果你想要 –
如果可能,這將是偉大的! – benlaplanche