2014-01-28 38 views
1

我有兩個模型profilereviewprofilepoints列,但我不知道我應該如何添加/更新點。如何添加/更新點在軌道中的特定屬性4

  • 如果用戶加上他的first name比2分應該加在積分欄中。
  • 如果用戶添加他的last name應該在點數列中添加2點以上。
  • 如果用戶加上他的phone應該在積分欄中加上5分以上。
  • 如果用戶添加slogan應該在點數列中加10分以上。

  • 如果配置文件有20分以上的20條評論應加點列。(1點每個評審)

你的幫助是非常讚賞。

Profile.rb

class Profile < ActiveRecord::Base 
    # :first_name 
    # :last_name 
    # :gender 
    # :phone 
    # :slogan 
    # :description 
    # :points 

    has_many :reviews 
end 

Review.rb

class Review < ActiveRecord::Base 
    belongs_to :profile 

    # :body 
end 

回答

2

你可以使用callbacks做到這一點。

changes告訴您對記錄的字段進行了哪些更改。因此,在上面的代碼中,檢查相關字段是否爲空,現在已填充,如果是,則在保存記錄之前將值添加到score字段。

class Profile < ActiveRecord::Base 
    before_save :update_score 

    private 

    def update_score 
    self.score += 2 if has_added?('first_name') 
    self.score += 2 if has_added?('last_name') 
    self.score += 5 if has_added?('phone') 
    self.score += 10 if has_added?('slogan') 
    end 

    def has_added?(field_name) 
    changes[field_name].present? && changes[field_name].first.nil? 
    end 
end 

對於審查的一部分,類似的:

class Review < ActiveRecord::Base 
    belongs_to :profile 

    after_save :update_profile_score, 
       if: Proc.new { |review| review.profile.reviews.count == 20 } 

    private 

    def update_profile_score 
    self.profile.score += 20 
    self.profile.save 
    end 
end 
+0

我得到一個錯誤「爲無未定義的方法'第一」:NilClass」 – Murtza

+0

@Murtza更新了答案。再檢查一遍。 – Agis

+0

非常感謝。它工作得很好。 – Murtza

0

我建議創建新類取計算點的責任。 然後,您可以在保存模型和更新點屬性之前使用此類來計算點。

此代碼未經測試,但應該給你的想法。

class PointCalculator 
    def initialize(profile) 
    @profile = profile 
    end 

    def calculate 
    first_name_points + last_name_points + phone_points + slogan_points + review_points 
    end 

    private 

    def first_name_points 
    @profile.first_name.present? ? 2 : 0 
    end 

    def last_name_points 
    @profile.last_name.present? ? 2 : 0 
    end 

    # (...) 

    def review_points 
    @profile.reviews.length 
    end 
end 

class Profile < ActiveRecord::Base 
    has_many :reviews 

    before_save :calculate_points 

    private 

    def calculate_points 
     self.points = PointCalculator.new(self).calculate 
    end 
end 
+0

謝謝你花時間寫這個答案,我會盡快測試你的代碼,如果它有效,我會接受答案。 – Murtza