开发者

Rails: How to validate data manually using a given model?

I am creating a Tumblr alternative to learn how use Rails. I am at the authentication part, and I decided to do it from scratch. I want to allow users to log in using either their开发者_开发百科 username or their email. The user logs in via the Sessions controller but I need to verify if the login is either a valid username or a valid email. So I need to validate data in the Sessions controller using the User model.

I found this answer on SO: How do I validate a non-model form in Rails 3? but it will force me to duplicate the validations. Is that the only way to do it, or is there another way that is cleaner?


The best option I can imagine is creating a module and then including it at your User model and at the object you're going to use for the form:

module AuthenticationValidation
  def self.included( base )
    base.validates :username, :presence => true
    base.validates :email, :presence => true
    # add your other validations here
  end
end

And then include this module at your models:

class User < ActiveRecord::Base
  include AuthenticationValidation
end

class LoginForm
  include ActiveModel::Validations
  include ActiveModel::Conversion      
  include AuthenticationValidation

  attr_accessor :username, :email
end

And then you have avoided repeating the validation itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜