【发布时间】:2013-03-17 03:51:44
【问题描述】:
我有一个简单的应用程序,其中包含用户模型、角色模型、带有收件人的消息模型。 一个用户通过角色有很多消息 并且一个角色有很多通过收件人的消息,而一个用户也有很多通过收件人的消息。
收件人模型有一个 user_id、role_id 和 message_id
现在我想在一个查询中显示用户的所有消息,包括他的角色消息和他的个人消息。我怎样才能做到这一点。
role model
has_many :recipients
has_many :received_messages, :class_name => 'Message', :order => 'created_at desc', through: :recipients
user model
has_many :roles
has_many :received_messages, :class_name => 'Message', :order => 'created_at desc', through: :roles, :uniq => true
has_many :recipients
has_many :private_messages, :class_name => 'Message', :order => 'created_at desc', through: :recipients
message model
has_many :recipients
has_many :roles, :through => :recipients
has_many :users, :through => :recipients
有了所有这些,我将如何获取用户消息,包括他的角色消息和他的私人消息
例子
def all_messages
@all_messages = current_user.#all messages scope here#
end
【问题讨论】:
-
你有 has_many :roles 用于用户模型。这意味着您在角色模型上有一个 belongs_to :user 对吗?
标签: ruby-on-rails ruby-on-rails-3 activerecord