所以我有一个编辑页面,上面有大量的可编辑字段......简单的更新......@patient.update_attributes(params[:patient])
……一切都很好,除了……
在这 20 个字段中,我有一个字段在准备好用于数据库之前需要稍微调整一下,看来我要么需要做
@patient.update_attributes(params[:patient])
@patient.update_attribute( :field=>'blah')
patient.update_attributes(:field1=>'asdf', :field2=>'sdfg',:field3=>'dfgh', etc...)
我错过了一种方法来做到这一点吗?
最佳答案
你需要调整的属性是什么?有两种方法可以做到这一点:
要么在将参数发送到 update_attribute 方法之前对其进行按摩:
如果您想强调其中一个值,我只是在这里举个例子:
params[:patient][:my_tweak_attribute].gsub!(" ", "_")
@patient.update_attributes(params[:patient])
然后是在模型中的 before_save 或 before_update 回调中进行调整的首选方法:
class Patient < ActiveRecord::Base
before_update :fix_my_tweak_attribute, :if => :my_tweak_attribute_changed?
protected
def fix_my_tweak_attribute
self.my_tweak_attribute.gsub!(" ", "_")
end
end
这使您的 Controller 保持干净,它可能并不真正需要的代码。
如果你只需要添加一个没有被表单发送的新参数,你可以在 Controller 中这样做:
params[:patient][:updated_by_id] = current_user.id
@patient.update_attributes(params[:patient])
假设
current_user
在某处为你定义(再次,只是一个例子)
关于ruby-on-rails - update_attributes 字段调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263844/