[英]Ruby on Rails: using nested named_scopes
我剛剛被一位朋友介紹到stackoverflow來解決我遇到的問題。 我對ruby剛起步還很陌生,我正在一個協作項目中,我們有一個腳本(medal_worker.rb),該腳本計划以固定的時間間隔運行,以基於我們網站上的各種參與和成功向人們授予各種獎章。 我正在研究的新勛章之一是獎勵人們“里程碑”。 出於這個問題的目的,假設我們要在他們發表100、1000和10000條評論時給他們獎牌。 我想通過使用來自User模型(user.rb)的named_scopes來給我尋找的用戶過濾列表來做到這一點。
我的問題是:如何找到沒有針對相應里程碑評論級別的勛章的用戶(最好使用User模型中的named_scopes)?
這是我的model_worker.rb文件的摘錄:
def award_comment_milestone(comments)
users = Users.frequent_comment_club_members(comments).not_awarded_medal(Medal.find_by_id(medal.id))
for user in users do
award_medal(medal, nil, user) if @award
end
end
這是我在用戶模型(user.rb)中使用named_scopes的位置:
named_scope :frequent_comment_club_members, lambda { |*args|
{:include => comment_records, :conditions => ['comment_records.comment_type = ? and comment_records.comments >= ?', 'User', (args.first || 0)]}
}
named_scope :not_awarded_medal, lambda { |medal|
{:include => :awards, :conditions => ['awards.medal_id not in (select awards.medal_id from awards where awards.medal_id = ?)", medal.id] }
}
這不是我想要的那樣,但是我不知道問題出在named_scopes還是我如何通過爭論或什么。 謝謝。
您的named_scopes
看起來不錯。 除非您在not_awarded_medal
條件語句中以單撇號開頭和以雙撇號結尾。
編輯 :
把它收回。 您的not_awarded_medal
named_scope已關閉。
嘗試這樣的事情:
named_scope :not_awarded_medal, lambda { |medal_id|
{ :include => :awards,
:conditions => [
"? not in (select awards.id from awards where awards.user_id = users.id)", medal_id
]
}
}
未經測試
現在,假設您具有以下關系:
User: has_many :awards
Award: belongs_to :user
如果您使用has_many :through
那么您將不得不更改SQL以查看聯接(users_awards)表。
-
但是我確實在award_comment_milestone
函數中看到了幾件事。
award_comment_milestone
什么參數? 它是評論數組還是評論計數? medal
在哪里定義?
如果comments
是一個數組,則需要將comments.length
傳遞給frequent_comment_club_members
。 如果是計數,那么我將其重命名為comments_count
以便下一個人可以更快地理解邏輯。
一些一般性的意見:
not_awarded_medal
應該只帶有一個badge_id,而不是整個對象(無需執行多個查詢) Medal.find_by_id(medal.id)
? 您已經擁有獎牌對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.