update_attributes中的意外','期待')' - Rails

Pal*_*ini 2 ruby database activerecord ruby-on-rails

我正在努力进行迁移,但我遇到了一些麻烦.当我尝试在Heroku上运行"rake db:migrate"时,我收到了一条错误消息.现在我在我的localhost中发现迁移中的代码有问题 - 但我不知道是什么.

这是我的迁移代码:

def change
    add_column :comments, :likes_count, :integer, :default => 0
    Comment.all().each do |comment|
        comment.update_attribute(:likes_count, comment.likes.count)
        comment.save        
    end
  end
Run Code Online (Sandbox Code Playgroud)

这是我在控制台上出现的错误(当我尝试在"rails console"上复制并粘贴此代码时):

 SyntaxError: (irb):3: syntax error, unexpected ',', expecting ')'
c.update_attribute (:likes_count, comment.likes.count)
                                 ^
(irb):3: syntax error, unexpected ')', expecting keyword_end
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

---------------------编辑---------------------------
The奇怪的是:我已经在localhost上运行了这个迁移,并且localhost中的所有东西都可以运行.但是当我尝试在Heroku上运行"rake db:migrate"时,我收到了一个错误 - 当我尝试在rails控制台上运行相同的代码时,我也遇到了错误(如上所示).

Mat*_*att 5

首先,您需要重置列信息,以便在向其添加值之前表了解其新列.

http://apidock.com/rails/ActiveRecord/Base/reset_column_information/class

你也不需要()Comment.all().each,Comment.all.each很好.你也不需要显式保存,update_attribute会为你保存更改(http://apidock.com/rails/ActiveResource/Base/update_attribute)

最后,您的错误消息与您的代码不匹配,方法调用中存在恶意空间:

c.update_attribute (:likes_count, comment.likes.count)
Run Code Online (Sandbox Code Playgroud)

删除那个空间

c.update_attribute(:likes_count, comment.likes.count)
Run Code Online (Sandbox Code Playgroud)

看看会发生什么.

编辑:修复后的迁移

def change
  add_column :comments, :likes_count, :integer, :default => 0

  Comment.reset_column_information

  Comment.all.each do |comment|
    comment.update_attribute(:likes_count, comment.likes.count)      
  end
end
Run Code Online (Sandbox Code Playgroud)