Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 更新另一个模型的属性_Ruby On Rails_Ruby On Rails 5 - Fatal编程技术网

Ruby on rails 更新另一个模型的属性

Ruby on rails 更新另一个模型的属性,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我有一个用户父模型和它的子模型注释。我希望在创建评论时更新用户的profile_rating属性。我正在尝试使用回调,并且在comment类中添加了一个方法。我不断收到错误“profile_rating is undefined”我做错了什么 class User < ApplicationRecord has_many :comments, dependent: :destroy end class Comment < ApplicationRecord b

我有一个用户父模型和它的子模型注释。我希望在创建评论时更新用户的profile_rating属性。我正在尝试使用回调,并且在comment类中添加了一个方法。我不断收到错误“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
class用户
尝试更改

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(user.profile_rating: @new_profile_rating)
end
致:

或:

或:

确保迁移中的
profile\u rating
的默认值为
0


确保在迁移中,
profile\u rating
的默认值为
0

它们都应该工作。试试看。另外,请随时为未来的搜索者投票/接受。@jvillian是否在创建后不应使用
:更新配置文件\u评级
,而不是在保存后使用
?@Gabbar-Welp,我不知道。OP在保存后指定
。这可能是正确的行为,也可能不是。鉴于提出的问题,很难说/知道。他们都应该工作。试试看。另外,请随时为未来的搜索者投票/接受。@jvillian是否在创建后不应使用
:更新配置文件\u评级
,而不是在保存后使用
?@Gabbar-Welp,我不知道。OP在保存后指定
。这可能是正确的行为,也可能不是。鉴于所提出的问题,很难说/知道。我如何将其设置为0?
t.integer:profile\u rating,默认值:在创建用户表的迁移中为0
。请确保回滚,然后再次运行迁移。如何将其设置为0?
t.integer:profile\u rating,默认值:在创建用户表的迁移中为0
。确保回滚,然后重新运行迁移。
def update_profile_rating
   user.update(profile_rating: user.profile_rating + 1)
end
def update_profile_rating
   user.increment!(:profile_rating)
end    
 def update_profile_rating
   user.update!(profile_rating: user.profile_rating + 1)
 end