简体   繁体   English

模型中的覆盖保存方法

[英]Overriding save method in model

I'm new to Ruby/Rails and I want to override the save method so I can do some checking inside myself before calling the actual save method, however, I am getting this exception for some reason: 我是Ruby / Rails的新手,我想重写save方法,以便在调用实际的save方法之前可以在自己内部进行一些检查,但是,由于某些原因,我遇到了此异常:

#<NoMethodError: undefined method `save' for true:TrueClass>

This is my code for the module and class. 这是我的模块和类的代码。

Module: 模块:

module OverrideSave

    def save
        super.save if some_condition_true
    end
  end

Class: 类:

class CardTransaction
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  prepend OverrideSave

  field :type, type: String
  field :transaction_value, type: BigDecimal
  field :receipt_value, type: BigDecimal
  field :store_id, type: String

  belongs_to :card
end

I'm not sure what went wrong, any ideas? 我不确定出了什么问题,有什么想法吗?

Why do you try to call save on whatever super (ie save ) returns? 为什么您尝试在super (即save )返回的任何值上调用save From your description, you want something like this: 根据您的描述,您需要这样的东西:

def save
  # some additional work
  super
end

You don't need to override the save method for above. 您不需要重写上面的save方法。 You can use before_save callback in your model: 您可以在模型中使用before_save 回调

class CardTransaction
  before_save :do_some_validation

  private

  def do_some_validation
    # will get there before the save is called
    false if custom_validation
  end
end

As stated by @Marek 正如@Marek所言

module OverrideSave

    def save
        super if some_condition_true
    end
end

But it is not good behavior to override save method, it would be better to create a new method which would use save method, so you still have save method. 但是重写save方法不是一个好习惯,最好创建一个使用保存方法的新方法,因此您仍然有save方法。

module OverrideSave
  def save_with_guard
     save if some_condition_true
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM