2

I not using ActiveRecords rather using ActiveModel to validate form data. I am stuck into some point where i needed to validate a form field depending on a radio button value.

My model is

 class Payment
    include ActiveModel::Model
    attr_accessor :method_id, :crad_name
    validates_presence_of :card_name, :if => :method_type? 

   private
   def method_type?
     self.method_id == 1
   end
 end

Here, method_id = 1 for credit card and method_id = 2 for bank

That does not validate the form field and does not show any error either.

I have searched in google and got some valuable stuff for here Rails - How to validate a field only if a another field has a certain value?

But it does not work in this case. Thanks in advance for your suggestion and help

Community
  • 1
  • 1
sukanta
  • 541
  • 6
  • 18

2 Answers2

0

You're almost there. I'd like to say first though that using Method as a model name isn't a great idea, as it's generally considered a reserved word. Moving on.

class Payment
  attr_accessor :method_id, crad_name
  validates_presence_of :card_name, :unless => :method_id.nil? 

end
trh
  • 7,186
  • 2
  • 29
  • 41
  • Thanks for your quick reply @trh but problem is i have two options for radio button method_id = 1 for credit card and method_id = 2 for Bank. – sukanta Oct 08 '15 at 00:12
0

Try this

class Payment
  include ActiveModel::Model
  attr_accessor :method_id, :crad_name
  validates_presence_of :card_name, :if => lambda { |pay| pay.method_id == 1 }
end

EDIT Try this or refer Active Record Validations

class Payment
  include ActiveModel::Model
  attr_accessor :method_id, :crad_name
  validates :card_name, presence: true, if: :method_type?

  private

  def method_type?
    method_id == 1
  end      
end

This should work for sure or god help me!

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88