开发者

Rails custom validation (reusable macro-style)

开发者 https://www.devze.com 2023-02-16 18:35 出处:网络
Writing a Rails app.I\'d like to make a few more commonly used validations available across my models.I understand how to do the built in validations, and how to write my own custom methods.However, I

Writing a Rails app. I'd like to make a few more commonly used validations available across my models. I understand how to do the built in validations, and how to write my own custom methods. However, I find that I'm using the same validations in a few places and it feels awkward to be using mixins on the different classes.

Here's an example: I have an object with prop1 and prop2. Either is valid, but it is not valid to set both. Right now, I have something like

class MyClass < ActiveRecord::Base 
  attr_accessor :prop1, :prop2
  validate :prop1_prop2_mutex

  def prop1_prop2_mu开发者_开发技巧tex 
     errors.add(:base, "Can not set prop1 and prop2") if prop1 && prop2
  end 
end

What I'd really like to have is something like

class MyClass < ActiveRecord::Base 
  attr_accessor :prop1, :prop2
  validate_mutex :prop1, :prop2
end 

and then somewhere else I'm guessing I'd need something like

  def validate_mutex(property1, property2)
    rrors.add(:base, "Can not set prop1 and prop2") if self.send(property1) && self.send(property2)
  end

That might not be that close.

So, how can I build in a new reusable validation method?

Or is there a better way to approach this problem?

Please be general. I have a few instances of this problem in different forms. Though I would appreciate a super-simple, built in solution to this example, I have more complex validations that I'd like to apply the solution to.


You can use the custom validators API to do things like:

validate :mutex => :prop1
0

精彩评论

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