2013-03-09 5 views
1

나는 사용자 모델, 역할 모델, 수신자가있는 메시지 모델을 가진 간단한 응용 프로그램을 가지고 있습니다. 사용자는 역할 을 통해 많은 메시지를 가지며 역할은받는 사람을 통해 많은 메시지를 가지며 사용자는받는 사람을 통해 많은 메시지를가집니다.레일에서 두 개의 ActiveRecord 쿼리를 연결하는 방법

받는 모델은 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 
+0

사용자 모델에는 has_many : roles가 있습니다. 즉, 역할 모델에 belongs_to : 사용자가 있다는 뜻입니까? – jvnill

답변

2

방법 중 하나를 가져 갈거야 all_messages 메소드에서 received_messages의 배열을 private_messages의 배열과 결합합니다. 그러면 모든 사용자의 메시지 배열이 반환됩니다.

def all_messages 
    (current_user.received_messages + current_user.private_messages).uniq 
end 
+0

니스. 덕분에, concat 메서드에 대해 전혀 새로운 적이 없습니다. – Uchenna

+0

나는 이것을 시험해 보았고 다음과 같은 오류가 발생했습니다. '사용자 # received_messages'가 하나 이상의 다른 연결을 통과하기 때문에 연결을 수정할 수 없습니다. ' – Uchenna

+0

쏴, 나는 그것을 간과했다. 예, ActiveRecord 연관을 통해 생성 된 배열 bc를 수정할 수 없습니다. 방금 내 대답을 업데이트했습니다. –

관련 문제