2010-01-03 6 views
1

가 나는 사용자들이이 배지하여 award_badge 방법의 실행을 획득 한 경우 "배지"레일,`flash [: notice]`?

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

를 취득하고 사용자에게 관련 배지를 제공 한 경우 보는 방법을 가지고있는 user 모델을 가지고 . 이런 식으로 할 수 있을까요?

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

빌어 먹을 좋은 답변. –

관련 문제