开发者

Ruby on Rails ActiveRecord Validation

开发者 https://www.devze.com 2022-12-12 02:58 出处:网络
I would like to validate attributes in a function like this class User < ActiveRecord::Base validate :che开发者_如何学JAVAck_name( :name )

I would like to validate attributes in a function like this

class User < ActiveRecord::Base

  validate :che开发者_如何学JAVAck_name( :name )

  def check_name( name )
    ... if name is invalid ...
       self.errors.add( :name, 'Name is invalid')
  end

end

Can you please write the right code? Please explain the functionality why... THX!


class User < ActiveRecord::Base

  validate :check_name

  def check_name
    if name # is invalid ...
      self.errors.add(:name, 'Name is invalid')
    end
  end

end

You can use the validate macro but the method can't accept parameters. You need to fetch the attribute value from inside the method, then validate it.

Replace

if name # is invalid ...

with your own validation logic.

0

精彩评论

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