ruby-on-rails - 使用 Active_record Dirty : Before @example. 更新(model_params)进行更改检测?

标签 ruby-on-rails ruby

我无法让脏模块工作。

我的方法在 Controller 中启动,在调用更新操作之前,我想查看模型是否已更改。像这样:

def update  
 respond_to do |format|
  #If the zipcode changes on an update - reset shipping options       
  if @order_preview.zip_different?
    if @order_preview.update(order_preview_params) 
      #Do Something
    ...
    end

  #if the zipcode doesn't change on update - assume only cart contents were altered
  else
     if @order_preview.update(order_preview_params) 
     #Do something else

     ...
     end
  end     
end

zip_different 模型如下所示:

def zip_different?
    self.zip_changed?
end

看起来很直接,但每次都返回 false。 我是否必须在 @order_preview.update(order_preview_params) 之后进行检查?我认为到那时,持久性将会丢失。

最佳答案

在检查脏状态之前,您需要从参数中设置模型属性:

@order_preview.attributes = order_preview_params

if @order_preview.zip_changed?
  ...
else
  ...

if @order_preview.save
  ...
else
  ...

关于ruby-on-rails - 使用 Active_record Dirty : Before @example. 更新(model_params)进行更改检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276690/

相关文章:

android - 来自 native Android 应用程序的 Rails 用户身份验证

ruby-on-rails - 简单消息系统的当前对话逻辑

ruby-on-rails - 无法弄清楚为什么我会收到单位化常量错误

ruby - 进入域后如何配置静默登录Redmine?

html - 在 View 中创建 Ruby on Rails 矩阵表

ruby-on-rails - rails : Why "format" (regex) validation fails?

ruby-on-rails - Activerecord 查询 .where 字符串作为数字

ruby-on-rails - 晒干萝卜步骤定义

ruby-on-rails - 当我尝试创建一个新项目时出现 Rails 错误

mysql - update_all 与字符串连接