How can I get validation "ifs" to use parameters (Ruby on Rails)
For condit开发者_StackOverflow社区ional validation in Rails, I can do this:
mailed_or_faxed_agenda = Proc.new { |me| me[:agenda_mailed_faxed] }
validates_presence_of :agenda, :if=>!mailed_or_faxed_agenda
but I don't know how to parameterize the Proc. I would love to use if=>blah(name)
but I cannot figure out how to it. Any ideas?
Note: In these ifs one can also use the name of a method, but as a symbol. I can't imagine how to pass parameters to that.
By "parameterize the Proc", do you mean currying?
Or just this?
my_proc = Proc.new { |chunky| do stuff to 'chunky' here }
my_proc.call("bacon") # "bacon" is "chunky" in the above proc
The second problem (sending params to a method), you can do something like this:
validates_presence_of :some_column_name
:if => Proc.new { |model_instance| model_instance.send(:some_method, arg1, arg2, arg3) }
Update:
The above can be simplified if you don't want to parameterize the method that is called. The following is equivalent to passing a literal symbol to send
:
validates_presence_of :some_column_name
:if => Proc.new { |model_instance| model_instance.some_method(arg1, arg2, arg3) }
Based on the documentation, you can use a proc in the :if parameter.
validates_presence_of :agenda,
:if => Proc.new { |me| me[:agenda_mailed_faxed] }
And you can also avoid using that proc by doing your method and passing it's name as a symbol.
def mailed_or_faxed
# Your method logic
end
validates_presence_of :agenda,
:if => :mailed_or_faxed
You can't provide any parameter to those if. But it's not necessary.
You have access to all the model's datas in the validation method.
For example if you want to check if the agenda_mailed_faxed boolean form value in your validation, doing the following will perfectly work :
validates_presence_of :agenda,
:if => :agenda_mailed_faxed
Your validations are executed inside your model, which is alread instantiated with all your form datas.
You can directly access them. No need to pass them as parameters.
精彩评论