如何在rails 4中添加/更新特定属性的点

时间:2014-01-28 17:29:38

标签: ruby-on-rails ruby

我有两个模型profilereviewprofilepoints列,但我不知道应该如何添加/更新积分。

  • 如果用户添加他的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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我建议创建新课程来负责计算积分。 然后,您可以在保存模型和更新points属性之前使用此类计算点。

这段代码未经测试,但应该给你一个想法。

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