我在使用以下应用程序时遇到问题,我一直在使用railsCasts的Rails 3中的第211集Validages,但是当我尝试添加类EmailFormatValidator时会触发错误
NoMethodError in Users#index
Showing /home/fernando/Validations/store/app/views/users/index.html.erb where line #12 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #12):
9: <th></th>
10: </tr>
11:
12: <% @users.each do |user| %>
13: <tr>
14: <td><%= user.name %></td>
15: <td><%= user.email %></td>
Rails.root: /home/fernando/Validations/store
模型/ user.rb
class User < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true
end
LIB / email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end
/controller/user.rb
class UsersController < ApplicationController
# GET /users
# GET /users.json
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
#GET / users / new #GET /users/new.json def new @user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
端
#GET / users / 1 /编辑 def编辑 @user = User.find(params [:id]) 端
#POST / users #POST /users.json def创建 @user = User.new(params [:user])
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
端
#PUT / users / 1 #PUT /users/1.json def更新 @user = User.find(params [:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
端
#DELETE / users / 1 #DELETE /users/1.json def destroy @user = User.find(params [:id]) @ user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
端 端
单击一次时会出现此错误 UsersController中的ArgumentError #index
Unknown validator: 'EmailFormatValidator'
Rails.root: /home/fernando/Validations/store
答案 0 :(得分:2)
请在app文件夹中创建验证器dir。
您的文件名应该与validators文件夹中的email_format_validator.rb类似
#app/model/user.rb
class User < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true
end
请从&#34; lib文件夹&#34;。
中删除此验证程序文件使用Devise
为电子邮件编写Rails验证的简单方法
更简单validates :email, :presence => true, :format => Devise.email_regexp