0
Like_id 및 user_id가있는 Like 모델이 있습니다. 그리고 메시지 모델 to_id와 from_id.복잡한 "간접적 인"연결
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :liked, :class_name => "User"
validates_presence_of :user_id
validates_presence_of :liked_id
def latest_message
Message.where(["(to_id = ? AND from_id = ?) OR (to_id = ? AND from_id = ?)", self.liked_id, self.user_id, self.user_id, self.liked_id]).order("created_at DESC").limit(1).first
end
end
class Message < ActiveRecord::Base
belongs_to :to, :class_name => "User"
belongs_to :from, :class_name => "User"
validates_presence_of :to_id, :from_id, :content
end
좋아요와 메시지 사이의 연결을 설정하고 하나의 쿼리에서 다시 가져올 수 있기를 원합니다.
현재 json serialization에서 : method => [: latest_message] 옵션을 사용하고 있습니다. 그러나 그것은별로 성과가 없습니다.
기본 키와 외래 키가 latest_message의 where 문과 같은 AND OR 일 때 이와 같은 복잡한 연관을 만들 수 있습니까? 이상 적으로 나는 has_one : latest_message를 원합니다.
을 참조하십시오. many to many 연관을 찾았습니까? (메시지 has_many : like : through => 'User') 문법을 용서하는 레일 녀석 아니에요. – Philip