【问题标题】:ActiveRecord having 2 FKs from the same column in a tableActiveRecord 具有来自表中同一列的 2 个 FK
【发布时间】:2014-05-18 18:51:30
【问题描述】:

您好,我想让我的用户互相发送消息,我想有一个类似的表结构

用户: 身份证 |名称

消息: 到 |从 |正文

我对 Rails 比较陌生,我不确定我的模型应该是什么样子,也不知道如何在我有来自同一列的两个 FK 的情况下建立关系。 To & From 是发送消息的用户和接收者。我正在为我的模型使用 ActiveRecord。

谁能让我在这里指出正确的方向?我有一种感觉我应该使用 have_many through 但我希望关系恰好是 2。

【问题讨论】:

  • 我的回答对你有用吗?
  • 我不确定当我创建表单以创建消息时我无法测试它很多我的单元测试失败并且我收到消息 First argument in form cannot contain nil or be空的。我现在正在努力解决这个问题
  • 好的。对你有帮助的别忘了接受:)
  • 没问题,我会尽快做的
  • 您的users_controller.rb 文件放置在哪个文件夹中。

标签: ruby-on-rails activerecord ruby-on-rails-4


【解决方案1】:

你可以这样做

#user.rb
Class User < ActiveRecord::Base

has_many :messages

end

#message.rb
Class Message < ActiveRecord::Base

belongs_to :sender,class_name => "User",foreign_key => 'from'

belongs_to :receiver,class_name => "User",foreign_key => 'to'

end

注意:最好也建议使用integer foreign_keys。如果您想更改foreign_keys,我建议使用名称sender_idreceiver_id

【讨论】:

  • 我在控制台中测试我的模型,Message 是唯一无法访问的模型。如果我删除 2 个 belongs_to 关系,它会抛出 NameError: undefined local variable or method `class_name' for #<0x007fbfbc11af48>
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 2022-01-21
  • 2010-10-09
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2012-12-29
相关资源
最近更新 更多