2013-08-05 3 views
0

pg 데이터베이스를 사용하여 Rails 응용 프로그램에서 작동 범위를 확보하는 데 어려움이 있습니다. groups_controller.rb의 show 페이지에서 created_at에 의해 정렬 된 두 가지 유형의 데이터를 표시하려고합니다. 첫 번째는 그룹에 가입 사용자이고, 두 번째 그룹에 대한 이벤트의 출석을 확인 한 결과이여러 모델을 결합하여 활동 피드 만들기

user joined group (7 minutes ago) 
user confirmed attendance (10 minutes ago) 
user joined group (15 minutes ago) 

처럼 함께 혼합 될 수있는 사용자 모델은 다음과 같다으로

Group.rb

has_many :memberships 
has_many :users, through: :memberships 

has_many :events 

User.rb

has_many :memberships 
has_many :groups, through: :memberships 

has_many :confirmations 
has_many :events, through: :confirmations 

Event.r B groups_controller.rb의 show 액션에서

has_many :confirmations 
has_many :users, through: :confirmations 

, 나는 지난 24 시간 동안 모든 결과를 얻을 수를 사용하는 목적으로 Time.now를 전달과 같은 recent_activities 액션을 만들어

def show 
@recent = Group.recent_activities(Time.now) 

end 

그러나 group.rb에 메서드를 작성하면 문제가 발생했습니다. 예를 들어,이 형식을 사용하는 경우

where(memberships: {created_at: ''} 

지난 24 시간 이내에 또는 지난 7 일 이내에 계산하는 방법을 알지 못했습니다. 어떻게해야하는지 다른 문제가 있다고 확신합니다. 어떤 팁? 그들이이 함께 시도 모든 mishapen

Group.rb 

scope :recent_activities, lambda {|time| 
    joins(:user, :membership, :confirmation, :event). 
    where(memberships: {created_at: ''}, 
      confirmations: {created_at: '' }) 

    } 

답변

1

나오는 것, 그래서 난 단지 내 인생에서 이러한 유형의 쿼리의 몇 가지를 작성했습니다 :

scope :recent_activities, lambda{ |time| 
    joins({:memberships => :users}, {:events => :confirmations}). 
    where('CAST(memberships.created_at as DATE) > :yesterday 
     AND CAST(confirmations.created_at as DATE) > :yesterday', 
     yesterday: Date.today - 1.days) 

} 

(당신은에 다음 관계를 추가 할 수 있습니다 당신의 그룹 모델 : 당신이 ago, since 방법을 사용할 수 있다는 것을 보여주기 위해이 답변을 추가

has_many :events 
has_many :confirmations, :through => :events 
+0

고맙지 만 작동하지 않습니다. 전체 방법을 쓸 수 있습니까? 솔루션에서 확인 및 그룹간에 연관성이 없음을 유의하는 것이 중요합니까? '그룹 has_many : 이벤트, 이벤트 has_many : confirmations' 또는 중요하지 않습니까? – Leahcim

+0

방금 ​​내 대답을 올렸습니다. 이것은 복잡한 관계로 달성하기위한 매우 복잡한 쿼리입니다! @Leahcim – MrYoshiji

1

.

time 매개 변수의 "지난 24 시간 이후"에 이와 같이 할 수 있습니다. 당신이 피드 활동을 만들려고으로

scope :recent_activities, lambda {|time| 
    joins(:user, :membership, :confirmation, :event). 
    where("memberships.created_at >= :twenty_four_hours_ago and confirmations.created_at >= :twenty_four_hours_ago", twenty_four_hours_ago: 24.hours.ago(time)) 
} 
+0

이 오류가 발생했습니다 :'Group에 'Association'confirmation '확인이 없습니다. 아마도 철자가 틀렸을까요? '그룹과 확인 사이에는 직접적인 관계가 없습니다. 거기에 대한 답을 수정하는 방법이 있습니까? 감사합니다 – Leahcim

+0

@ Lehcim, 당신은 이미 해결책을 찾은 것 같습니다. 요시지 씨가 지적했듯이, 당신은 'has_many : confirmations, through : : events'를 정의 할 필요가있었습니다. – vee

0

, 그것은 당신을 도울 수, this 보석 좀 봐.
너도 알다시피 railscasts