ruby-on-rails - 如何在 rubyonrails 中命名外键?
问题描述
我解释我的问题:
我有 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 中解释这一点?
干杯。
解决方案
让我们交换名称sender
,recipient
这将使这更容易理解。
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
看:
推荐阅读
- python - Python 将类实例传递给方法并修改属性会导致新的、不相关的实例更改默认行为
- python - 使用 selenium python 在网站上匹配以前的工作日期
- django - 我想将产品添加到我的购物车并显示购物车详细信息..我无法理解为什么代码没有在页面上显示详细信息?
- google-chrome - 是否可以从本地文件系统加载用户脚本?
- javascript - 通过子对象的属性过滤对象的父子数组
- javascript - Nightmare JS 点击集合中的随机链接
- javascript - iOs 和 macOS (CSS3 + jQuery) 上的 PNG 动画问题
- javascript - 谷歌脚本中对服务器端函数的异步调用
- apache - 使用 Apache 测试我的 Web 服务器时出现问题,指定的超时已过期 (70007) Apache
- python - 使用 redis 和 python 的复杂查询