2

メールフィールドを持つビルダーとユーザーモデルがあり、両方のモデルでメールを一意にしたい。以下の検証方法は、ユーザーモデルではなくビルダーモデルに入れると正常に機能します。

class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable, :confirmable
attr_accessible :email, :password, :password_confirmation, :remember_me,:confirmation_token, :confirmed_at, :confirmation_sent_at, :unconfirmed_email, :provider,:uid, :name, :oauth_token, :oauth_expires_at
validate :check_email_exists

def check_email_exists
if Builder.exists?(:email => self.email)
  errors.add(:email,"User already exists with this email, try another email")
end
end 

エラーは次のとおりです。

NoMethodError in Devise::RegistrationsController#create 

app/models/user.rb:30:in `check_email_exists'

{"utf8"=>"✓",
"authenticity_token"=>"EiFhJta51puZ7HZA3YzhopsKL2aJWllkl8geo3cL3gc=",
"user"=>{"email"=>"builder@gmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}

エラーの理由は何ですか?私は何日もの間それを解決しようとしていますが、成功していません。

これは私のビルダーモデルです

class Builder < ActiveRecord::Base
devise :database_authenticatable, :registerable,
attr_accessible :email, :password, :password_confirmation, :remember_me,

validate :email_exists

def email_exists
if User.exists?(:email => self.email)
  errors.add(:email,"User already exists with this email, try another email")
end
end 

abc@gmail.com が User に既に存在する場合、Builder サインアップ フォームで abc@gmail.com を使用してサインアップすると、Builder サインアップ フォームはユーザーがすでに存在することを通知します。つまり、ビルダー モデルで email_exists が正常に動作していることを意味しますが、コードは正しいのに、ユーザーモデルをチェックインするとエラーがスローされるのはなぜですか。

class User < ActiveRecord::Builder

エラーが発生します: /home/rails/Desktop/realestate/app/models/user.rb:1:in <top (required)>': uninitialized constant ActiveRecord::Builder (NameError) from /home/rails/.rvm/gems/ruby-1.9.3-p448/gems/activesupport-3.2.13/lib/active_support/inflector/methods.rb:230:inblock in constantize'を終了しています

4

2 に答える 2

1

ActiveRecord スコープで定義されているモジュールをBuilder参照しているエラーからのようです。ActiveRecord::Associations::Builder

でモデルにアクセスしてみてください::Builder

  if ::Builder.exists?(email: email)
于 2013-09-23T08:06:03.430 に答える
0

一意性のためにデフォルトの検証を使用しないのはなぜですか

class User < ActiveRecord::Base
  ...
  validates :email, :uniqueness => true, :message => "User already exists with this email, try another email"
  ...
end

また、上記のコードでは、ビルダーの代わりにユーザーモデルを使用する必要があります

class User < ActiveRecord::Base
  ...
  def check_email_exists
    if User.exists?(:email => self.email)
      errors.add(:email,"User already exists with this email, try another email")
    end
  end 
  ...
end
于 2013-09-23T07:50:53.390 に答える