我有困難得到一個範圍與PG數據庫中的Rails應用程序的工作。在groups_controller.rb的顯示頁面中,我試圖顯示由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
has_many :confirmations
has_many :users, through: :confirmations
在groups_controller.rb的表演動作,我創造了這樣的recent_activities動作,傳遞Time.now並打算用它來獲取所有在過去24小時內的結果
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: '' })
}
感謝,但它不工作。你能寫出整個方法嗎?注意確認和組之間沒有關聯對您的解決方案來說很重要。 '組has_many:事件,事件has_many:確認'或者這沒關係? – Leahcim
我剛剛上傳了我的答案。這是一個非常複雜的查詢,用複雜的關係來實現! @Leahcim – MrYoshiji