如果不选择 updated_at 属性,则无法在 Rails 4 中更新模型 [英] Can't update model in Rails 4 without selecting updated_at attribute

查看:31
本文介绍了如果不选择 updated_at 属性,则无法在 Rails 4 中更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 rails 3.2.13 升级到 4,但在更新模型时遇到了问题.我试图在只有 id 的模型上更新单个属性,我还需要验证和回调.这在 rails 3 中运行良好,但在 rails 4 中遇到了问题.

I'm upgrading from rails 3.2.13 to 4 and ran into an issue updating models. I'm trying to update just a single attribute on a model where I have only the id, I also want validations and callbacks. This worked fine in rails 3 but I'm having trouble in rails 4.

在 Rails 4 中,如果我这样做:

In rails 4 if I do:

user = User.select(:id).first
user.first_name = 'name'
user.save!

我收到错误:

NoMethodError: undefined method `type_cast' for nil:NilClass
    from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/activerecord-4.0.3/lib/active_record/attribute_methods/time_zone_conversion.rb:10:in `type_cast'

如果我在 rails 3 中运行相同的代码,first_name 会更新,updated_at 会使用 current_time 进行更新.

If I run the same code in rails 3 first_name is updated and updated_at is updated with the current_time.

如果在 rails 4 中运行:

If in rails 4 I run:

user = User.select(:id, :updated_at).first
user.first_name = 'name'
user.save!

一切正常.

我认为错误是由于updated_at 列不存在而引起的,但它不应该存在.在我的许多查询中,我只选择 id 来表示速度.Rails 3 完美地处理了这个问题.我也使用 update_attributes 尝试过这个,但我收到了同样的错误.当我使用 update_column 时它可以工作,但它会跳过我想要的验证和回调.

I assume the error is caused by the fact that the updated_at column is not there, but it shouldn't need to be. In many of my queries I select only the id for speed. Rails 3 handled this perfectly. I also tried this using update_attributes but I received the same error. It works when I use update_column but then it skips validation and callbacks which I want.

我不确定为什么在 rails 4 中会发生这种情况,或者如何在 update_column 之后不显式调用验证和回调或选择我不需要的 updated_at 属性的情况下绕过.

I'm not sure why this is happening in rails 4 or how to get around without explicitly calling validation and callbacks after update_column or selecting the updated_at attribute which I shouldn't need to do.

推荐答案

我也遇到了.

问题似乎是没有加载updated_at.当您 update_attribute 时,它​​也会尝试更新 updated_at.它试图找到对该列进行类型转换的方法,但由于未选择该列而未加载该列.

The problem seems to be that updated_at is not loaded. When you update_attribute, it will try to update updated_at too. It tries to find the way to type cast that column but somewhere the column is not loaded because not selected.

对我来说,这是 Rails 中的一个错误.但也许它就是这样设计的.

For me this is a bug in Rails. But maybe it is intended to be like that.

一旦我在一个独立的 ruby​​ 文件中重现了这个错误,我就会在 GitHub 上的 rails/rails 上打开一个问题.将使用链接更新此帖子.

I will open an issue on rails/rails on GitHub as soon as I reproduced the bug in a standalone ruby file. Will update this post with the link.

这篇关于如果不选择 updated_at 属性,则无法在 Rails 4 中更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆