Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.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 未定义的方法`user';对于#<;类别:0x00007ffbd1c309b8>;_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 未定义的方法`user';对于#<;类别:0x00007ffbd1c309b8>;

Ruby on rails 未定义的方法`user';对于#<;类别:0x00007ffbd1c309b8>;,ruby-on-rails,ruby,Ruby On Rails,Ruby,我不明白为什么我不能在这里使用self class PayoutRequest < ApplicationRecord validates :phone, confirmation: true, on: :create validates :phone_confirmation, presence: true, on: :create belongs_to :user, foreign_key: "user_id" validates :amount,

我不明白为什么我不能在这里使用self

class PayoutRequest < ApplicationRecord
  validates :phone, confirmation: true, on: :create
  validates :phone_confirmation, presence: true, on: :create
  belongs_to :user, foreign_key: "user_id"
  validates :amount, numericality: { only_integer: true, greater_than_or_equal_to: 300, smaller_than_or_equal: self.user.balance }

  scope :paid, -> { where(:paid => true) }
  scope :unpaid, -> { where(:paid => false) }
end
class PayoutRequest{where(:paid=>true)}
范围:未付,->{where(:paid=>false)}
结束

因为
自我
不是你想象的那样。如果您不知道或忘记,验证DSL只是类本身调用的方法。在这里,您基本上调用
PayoutRequest。验证
并向其传递一些参数

validates :amount, numericality: { only_integer: true, greater_than_or_equal_to: 300, smaller_than_or_equal: self.user.balance }
^           ^ arg     ^ kw arg   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
method name                                 just a regular hash, defined at the class level. So `self` is the class.
我怎么写这个

使用自定义方法,例如:

validate :amount_not_greater_than_balance

def amount_not_greater_than_balance
  return if amount <= user.balance
  errors.add(:amount, "can't be greater than balance")
end
验证:金额不大于余额
def金额不大于余额

如果返回金额,那么我如何写入?您可以使用自定义方法:。这些都是在实例级别执行的。“变得小于用户的平衡”-您这里的意思是“更多/更大”?总的来说,我不确定这个建议。我想我不明白为什么不在更新上运行此验证。我们不想创建超过用户余额的付款请求,也不想让它变成这样。是的,对不起,我的意思是更多。已修复。@SergioTulentsev假设用户有100美元,并要求支付80美元。好的$80美元是从他们的账户中支付的,所以现在他们的账户中只有20美元。但这是否意味着他们最初的
支付请求应该已经无效??!这就是为什么我建议这样的验证只在创建时才有意义,而不是在以后的任意时刻。如果它再次移动到
挂起
,是的,它应该是无效的。:)