Обновить атрибут другой модели - PullRequest
0 голосов
/ 10 декабря 2018

У меня есть родительская модель 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 голосов
/ 10 декабря 2018
 def update_profile_rating
   user.update!(profile_rating: user.profile_rating + 1)
 end

Убедитесь, что значение по умолчанию profile_rating равно 0 в миграциях.

0 голосов
/ 10 декабря 2018

Попробуйте изменить

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    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...