Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.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 RubyonRails检测更新中属性的变化_Ruby On Rails_Ruby_Ruby On Rails 4.2 - Fatal编程技术网

Ruby on rails RubyonRails检测更新中属性的变化

Ruby on rails RubyonRails检测更新中属性的变化,ruby-on-rails,ruby,ruby-on-rails-4.2,Ruby On Rails,Ruby,Ruby On Rails 4.2,嗨,我有一个Rails应用程序,我想知道散列中的属性是否发生了更改 让我解释一下,我有@user的参数 "foo"=> {"name"=> "name1", "age"=> "15", "height"=> "120"} 现在,当我只更改属性age时,我想知道是否更改了age 我尝试的是@user.foo\u已更改?但只要foo哈希中有任何更改,它就会为true,但我希望只有在年龄更改时它才为true。如何实现这一点?Ruby on Rails提供了一些方法: obje

嗨,我有一个Rails应用程序,我想知道散列中的属性是否发生了更改 让我解释一下,我有@user的参数

"foo"=> {"name"=> "name1", "age"=> "15", "height"=> "120"}
现在,当我只更改属性age时,我想知道是否更改了age


我尝试的是
@user.foo\u已更改?
但只要foo哈希中有任何更改,它就会为true,但我希望只有在年龄更改时它才为true。如何实现这一点?

Ruby on Rails提供了一些方法:

object.attribute_changed?
例如:

User.first.name_changed?
你试过这个吗

@user.age_changed?
您可以找到更多信息,请尝试:

if @user.foo.age == params[:user][:foo][:age]
     # not changed
else
    # changed
end

@user.foo.age_changed?  # this will work in case foo is associated(nested) model with user and foo table has "age" field

是否要在更新后或更新前检查?@GaganGami before updatei如果
foo
是JSON或hstore列,则不可能。Rails更改跟踪只在列/属性上工作,不执行任何“深度”检查。这给出了未定义的方法age\u changed?如果我有另一个hash as bar,它也包含age,那么答案将与此冲突,但无论如何,它给出的是未定义的method@user4965201字体检查我的答案,让我知道Rails 5.1+是否适用于您此行为将改变:您的旧版本仅适用于。。这不起作用,它说未定义的方法age for#实际上在我的表中foo是一列,它包含如下值{“name”=>“name1”,“age”=>“15”,“height”=>“120”}@user4965201:我已经更新了这两个解决方案,如果它对您有帮助,您可以接受它