更新另一个模型的属性

时间:2018-12-10 18:12:24

标签: ruby-on-rails ruby-on-rails-5

我有一个User父模型,它是子模型Comment。每当创建评论时,我都希望更新到User的profile_rating属性。我正在尝试使用回调,并且在注释类中添加了一个方法。我不断收到错误消息“ profile_rating is undefined”,我在做什么错了?

class User < ApplicationRecord
   has_many :comments,
     dependent: :destroy
end

class Comment < ApplicationRecord

  belongs_to :user

  #update profile rating 
  after_save :update_profile_rating

  def update_profile_rating
     @new_profile_rating = user.profile_rating + 1
     User.update(user.profile_rating:  @new_profile_rating)
  end
end

2 个答案:

答案 0 :(得分:2)

尝试更改

def update_profile_rating
   @new_profile_rating = user.profile_rating + 1
   User.update(user.profile_rating: @new_profile_rating)
end

收件人:

def update_profile_rating
   @new_profile_rating = user.profile_rating + 1
   user.update(profile_rating: @new_profile_rating)
end

或:

def update_profile_rating
   user.update(profile_rating: user.profile_rating + 1)
end

或:

def update_profile_rating
   user.increment!(:profile_rating)
end    

答案 1 :(得分:0)

 def update_profile_rating
   user.update!(profile_rating: user.profile_rating + 1)
 end

确保迁移中的profile_rating的默认值为0

相关问题