2010-01-03 79 views
1

我有一個user模型中,我有一個方法,如果用戶贏得了「徽章」rails,`flash [:notice]`在我的模型中?

def check_if_badges_earned(user) 
    if user.recipes.count > 10 
    award_badge(1) 
end 

如果他們贏得了一個徽章,則該award_badge方法運行,併爲用戶提供相關的徽章看到。我可以做這樣的事嗎?

def check_if_badges_earned(user) 
    if user.recipes.count > 10 
    flash.now[:notice] = "you got a badge!" 
    award_badge(1) 
end 

獎勵問題!(瘸子,我知道)

會在哪裏,我把所有的這些「條件」這我的用戶可以賺取徽章最好的地方,類似stackoverflows徽章我想。我的意思是在架構方面,我已經有badgebadgings型號。

我該如何組織他們賺取的條件?其中一些變化複雜,比如用戶已經登錄了100次而沒有評論一次。等等,所以似乎沒有一個簡單的地方來放這種邏輯,因爲它涵蓋了幾乎所有的模型。

回答

4

我很抱歉,但在模型中無法訪問閃存散列,它會在您的控制器中處理請求時創建。您仍然可以使用您的實現方法存儲徽章的相關信息(包括閃存消息)在屬於您的用戶徽章對象:

class Badge 
    # columns: 
    # t.string :name 

    # seed datas: 
    # Badge.create(:name => "Recipeador", :description => "Posted 10 recipes") 
    # Badge.create(:name => "Answering Machine", :description => "Answered 1k questions") 
end 

class User 
    #... 
    has_many :badges  

    def earn_badges 
    awards = [] 
    awards << earn(Badge.find(:conditions => { :name => "Recipeador" })) if user.recipes.count > 10 
    awards << earn(Badge.find(:conditions => { :name => "Answering Machine" })) if user.answers.valids.count > 1000 # an example 
    # I would also change the finds with some id (constant) for speedup 
    awards 
    end 
end 

則:

class YourController 
    def your_action 
    @user = User.find(# the way you like)... 
    flash[:notice] = "You earned these badges: "+ @user.earn_badges.map(:&name).join(", ") 
    #... 
    end 
end 
+0

一個該死好的答案。 – 2010-01-04 03:56:03

相關問題