首页 > 解决方案 > 如何在 ruby​​onrails 中命名外键?

问题描述

我解释我的问题:

我有 2 个模型:

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

我想要外键:

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

在我的模型中:

USER
-> has_many :messages

MESSAGE
-> belongs_to :users

在我的架构迁移中:

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

两个外键如何工作?如何在我的 messages_controller.rb 中解释这一点?

干杯。

标签: ruby-on-railsrubymodelcontrollerrubygems

解决方案


让我们交换名称senderrecipient这将使这更容易理解。

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

看:


推荐阅读