我一直在尝试比较 rails 中的两个对象,第一个来自新记录,另一个是数据库中的记录,但我还没有实现,我一直在做的是以下内容:
def update
new_biological_target = params[:biological_target]
old_biological_target = BiologicalTarget.find(params[:biological_target][:id])
if new_biological_target == old_biological_target
message="Equals"
else
message="different"
end
end
我想比较的是,如果用户对注册表进行了任何更改
正如其他人在这里提到的,您正在比较两种不同的类型。我假设您正在比较 Hash 和 BiologicalTarget。
一种解决方案是循环遍历 new_biological_target,并将 new_biological_target 的值与 old_biological_target 记录中的值进行比较。
# can initially set message to equal
message = 'equal'
new_biological_target.each do |key, value|
# make sure the record even has the attribute, then if it does, check to see if the values are the same
if old_biological_target.has_attribute?(key) && old_biological_target.attributes[key] == value
# move to next iteration of loop because the attribute was the same as value
next
# the params you are passing either have additional keys that aren't contained in the record, so handle however you want, in this case I am saying the object is different, or the value was different for the key
else
message = 'different'
break
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句