That was a fanatstic reply.
Hi everyone, I'm writing a form object powered by dry-validation. Let's say the form has two keys - :code and :organization_id.
I want to validate whether a pair [:code, :organization_id] is unique in my db, yet I'm failing in doing so.
First I though about using
rule(uniq_code: [:code, :organization_id]) but it clearly wants me to run predicates on the keys I've passed into it, so I decided to go with my custom predicate and ended up with the following
Create = Dry::Validation.Form do key(:code).required(uniq?: "organization_id") key(:name).required key(:countries_id).required key(:description).required key(:organization_id).required key(:active).required configure do option :market_repo, WheelsApp.instance["repositories.market"] def uniq?(organization_id, value) # query logic here end end
How can I pass to
uniq? method a value of :organization_id that comes from object I've passed into the form?
value(:organziation_id)but that returns something like an ast graph
codeto be values, not
unique?method's body and returned false explicitly, and the rule(:uniq_code_organization) failed, because it didn't expected to receive a FalseClass object.
.inspectoutput of the arguments?
module Dagavel::Predicates include Dry::Logic::Predicates predicate( :is_conversion_correct? ) do |exchange_rate_usd_points, points, usd| points_in_usd = ( Auction.convert_points_to_money( points, exchange_rate_usd_points ) * 100 ).floor usd = ( usd * 100 ).floor usd == points_in_usd end end ... rule( start_bid_conversion_is_correct: [ :start_bid_in_points, :start_bid_in_usd, :exchange_rate_usd_points ] ) do |start_bid_in_points, start_bid_in_usd, exchange_rate_usd_points| ( start_bid_in_points.int? & start_bid_in_usd.float? & exchange_rate_usd_points.int? ).then( start_bid_in_usd.is_conversion_correct?( start_bid_in_points, exchange_rate_usd_points ) ) end