Ruby on rails 在模型中进行验证之前,如何从中获取消息给用户

Ruby on rails 在模型中进行验证之前,如何从中获取消息给用户,ruby-on-rails,Ruby On Rails,我有以下代码,确保没有用户将系统用作垃圾邮件机器人。在模型ShopInvite中,我有以下代码: before_validation(on: :create) do !(ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).where(:sender_ip => self.sender_ip).count > 2) end 这是可行的,但如何将“由于垃圾邮件保护而不发送”的消息获取到视图中?

我有以下代码,确保没有用户将系统用作垃圾邮件机器人。在模型ShopInvite中,我有以下代码:

  before_validation(on: :create) do
    !(ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).where(:sender_ip => self.sender_ip).count > 2)
  end

这是可行的,但如何将“由于垃圾邮件保护而不发送”的消息获取到视图中?

只需在实例中添加一个错误:

before_validation(on: :create) do
  if (ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).where(:sender_ip =>  self.sender_ip).count > 2)
    errors[:base] << 'cannot be sent due to spam protection'
    false
  else
    true
  end
end
在验证(on::create)之前
if(ShopInvite.where(“创建时间>=?”,Time.now.ago(60.minutes)).where(:sender\u ip=>self.sender\u ip).count>2)

错误[:base]只需将错误添加到实例:

before_validation(on: :create) do
  if (ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).where(:sender_ip =>  self.sender_ip).count > 2)
    errors[:base] << 'cannot be sent due to spam protection'
    false
  else
    true
  end
end
在验证(on::create)之前
if(ShopInvite.where(“创建时间>=?”,Time.now.ago(60.minutes)).where(:sender\u ip=>self.sender\u ip).count>2)

错误[:base]我想这就是你想要的。 请注意,通过自定义方法验证是复数validate

class ShopInvite < ActiveRecord::Base
  validate :message_to_user

def message_to_user

 if (ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).
     where(:sender_ip => self.sender_ip).count > 2)
     errors[:base] << 'cannot be sent due to spam protection'
     false
  else
    true
  end
end
end
class ShopInvite=?”,Time.now.ago(60.minutes))。
其中(:sender\u ip=>self.sender\u ip).count>2)

错误[:base]我想这就是你想要的。 请注意,通过自定义方法验证是复数validate

class ShopInvite < ActiveRecord::Base
  validate :message_to_user

def message_to_user

 if (ShopInvite.where("created_at >= ?", Time.now.ago(60.minutes)).
     where(:sender_ip => self.sender_ip).count > 2)
     errors[:base] << 'cannot be sent due to spam protection'
     false
  else
    true
  end
end
end
class ShopInvite=?”,Time.now.ago(60.minutes))。
其中(:sender\u ip=>self.sender\u ip).count>2)

错误[:base]您可以发布依赖于此验证的控制器代码吗?您可以使用对象实例(在控制器中)中的
valid?
方法将消息传递到视图中。是否可以发布依赖于此验证的控制器代码?您可以在对象实例(在控制器中)中使用
valid?
方法将消息传递到视图中。不过,请注意,与任何
回调之前的
一样,如果且仅当返回false时,它将停止执行。因此,此定义在功能上与原始定义不同,在所有情况下都返回“非false”的内容。不过,请注意,与任何回调之前的
一样,当且仅当它返回false时,它将停止执行。因此,该定义在功能上与原始定义不同,在所有情况下都返回“非虚假”的内容。