ruby-on-rails - rails : How to enter value A in Model X only if value A exists in Model Y?

标签 ruby-on-rails ruby ruby-on-rails-3

我正在尝试构建一个注册模块,只有当用户的电子邮件已经在现有数据库中时,用户才能注册。

模型:

  1. 用户
  2. 老用户

用户的条件将是

if OldUser.find_by_email(params[:UserName]) exists, allow user registration.
If not, then indicate error message.

这在 PHP 中非常简单,我只需运行一个函数来执行 mysql 查询。但是,我无法弄清楚如何在 Rails 上执行此操作。看起来我必须创建一个自定义验证器函数,但对于这样一个简单的条件似乎有点过头了。

做起来应该很简单。我错过了什么?

有什么指示吗?

编辑 1:

dku.rajkumar 的这个解决方案稍作修改:

validate :check_email_existence
    def check_email_existence
      errors.add(:base, "Your email does not exist in our database") if OldUser.find_by_email(self.UserName).nil?
    end

对于这种情况,是在模型中还是在 Controller 中进行验证更好?

最佳答案

你可以这样做

if OldUser.find_by_email(params[:UserName])
   User.create(params) // something like this i guess
else
   flash[:error] = "Your email id does not exist in our database."
   redirect_to appropriate_url
end

更新:模型中的验证,因此验证将在调用 User.create

时完成
class User < ActiveRecord::Base

  validates :check_mail_id_presence

// other code
// other code

  private

  def check_mail_id_presence
     errors.add("Your email id does not exist in our database.") if OldUser.find_by_email(self.UserName).nil?
  end

end

关于ruby-on-rails - rails : How to enter value A in Model X only if value A exists in Model Y?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10662216/

相关文章:

ruby-on-rails - 令人难忘的 ruby 名称生成器 gem

ruby - 为什么我会有很多关系?

ruby - 如何修复此错误 : kernel_require. rb :45:in `require' : cannot load such file?

ruby-on-rails - 需要帮助最大化多个相似对象中的 3 个因素并适当排序

ruby-on-rails - 无法捕获 Rails 中的 Mysql2::Error

ruby-on-rails - Rails、PostgreSQL 和历史触发器

ruby - content_tag 条件 HTML 属性

ruby-on-rails - 如何在 Ruby on Rails 中使用 namespace 重写 URL?

ruby-on-rails-3 - 带有 :remote=>true and including :class and :id 的 rails3 中 block 的 link_to 的语法

ruby-on-rails - 资源路径如何工作(内部)?我需要修复的不良行为