1

我的模型中有以下关系:

class User < ActiveRecord::Base
  has_one :tutor, dependent: :destroy
  has_many :messages
end

class Tutor < ActiveRecord::Base
  belongs_to :user
  has_many :messages, :foreign_key => 'recipient_id'
end

class Message < ActiveRecord::Base
  belongs_to :users
  belongs_to :tutors
end

在我的消息索引视图中,我想做一个类似于收件箱的东西,其中显示与该消息关联的用户名。我尝试在控制台中执行 Message.first:

 Message.first   Message Load (0.3ms)  SELECT "messages".* FROM
 "messages" ORDER BY "messages"."id" ASC LIMIT 1  => #<Message id: 1,
 subject: "some subject", body: "and some body", created_at:
 "2013-09-01 13:09 :57", updated_at: "2013-09-01 13:09:57", user_id: 1,
 recipient_id: 2>

如果我这样做Message.first.users,我会得到:

 Message.first.users   Message Load (0.3ms)  SELECT "messages".* FROM
 "messages" ORDER BY "messages"."id" ASC LIMIT 1  => nil

我基本上想usernamerecipient_id. 我是否设置不正确?我应该做一个加入还是什么?

4

1 回答 1

3

belongs_to在模型中的关联声明Message不正确。详情请参考“ Belongs_to Association ”。

因此,更新您的Message模型应该可以解决问题:

class Message < ActiveRecord::Base
  # use singular :user and :tutor here

  belongs_to :user 
  belongs_to :tutor
end

然后,您将使用以下命令查询您的消息的用户:

Message.first.user
于 2013-09-01T15:11:59.790 回答