1

I explain my problem:

I have 2 models:

- User (id, firstname, lastname, deviceid, email, password);
- Message (id, fromuser, touser, description)

I want foreign-keys:

-: fromuser (Message) -> id (User)
-: touser (Message) -> id (User)

in my model:

USER
-> has_many :messages

MESSAGE
-> belongs_to :users

in my schema migrations:

create_table "messages", force: :cascade do |t|
t.string "description"
t.integer "fromuser"
t.integer "touser"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end

create_table "users", force: :cascade do |t|
t.string "firstname"
t.string "lastname"
t.string "deviceid"
t.string "email"
t.string "password"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end

How can both foreign-key work? How can explain this in my messages_controller.rb?

Cheers.

Finn
  • 23
  • 4
  • I think you need one more model... like Room Or Conversation which have both fromuser_id and touser_id and then associate it with Conversation has_many messages and User has many conversations.... etc etc.... – code_aks Oct 29 '19 at 14:26
  • 1
    @code_aks I don't think he needs another model, he can just query all messages where `fromuser` is some id and `touser` is some id and sort them by `created_at`. That's your conversation – Viktor Oct 29 '19 at 14:30

1 Answers1

6

Lets swap the names to sender and recipient which will make this a lot more understandable.

class User
  has_many :sent_messages,
     class_name: "Message",
     foreign_key: :sender_id
  has_many :recieved_messages,
     class_name: "Message",
     foreign_key: :recipient_id

  def conversation_with(other_user)
     Message.where(
       "(recipient_id = :a AND sender_id = :b) OR (recipient_id = :b AND sender_id = :a)", 
       a: self.id, b: other_user.id
     ).order(:created_at)
  end
end

class Message
  belongs_to :sender, class_name: 'User'
  belongs_to :recipient, class_name: 'User'
end

See:

max
  • 96,212
  • 14
  • 104
  • 165