Peter
Peter

Reputation: 3

How to validate input which depends on checkbox

I recently started with rails. I have one task here, but I don't know what is best practice and how to do it.

I have form with checkbox currency? and input currency_code. Only value currency_code will be stored in database.

What I need: 1. If checkbox currency? is TRUE => currency_code must be filled 2. If checkbox currency? is FALSE => currency_code will be reset to nil

How to validate 1. if currency? is not in database (table column) so model does not know about this? In case 2. Where I should check this and reset value currency_code to nil?

For case 2. I have this in my controller, but I don't like. I think that there must be a better solution.

def data_params
  parameters = params.require(:data).permit(
    :currency_code
  )
  parameters[:currency_code] = nil unless params[:data][:currency].to_bool
  parameters
end

Upvotes: 0

Views: 61

Answers (2)

Suganya Selvarajan
Suganya Selvarajan

Reputation: 1082

The attribute 'currency?' which is not part of the model is called virtual attributes. In Rails, we can use virtual attributes by setting

attr_accessor :currency?

in your corresponding_model.rb.

Now you can use this 'currency?' attribute in your form like other model attributes.

For case 2, the plcaement for this kind of data validations is to validate them in the view before even coming into the model. you must use jquery / javascript or any script of your choice. Here I provide jQuery snippet.

If you are new for using jquery in rails app, follow this https://github.com/rails/jquery-rails

In your form_page.html.erb add ids to the html elements.

<%= f.check_box :currency?, id: 'currency_checkbox' %>

and

<%= f.text_field :currency_code, id: 'currency_code' %>

The jquery snippet

curreny_checkbox = $('#curreny_checkbox')
currency_code = $('#currency_code')

$(currency_checkbox).on('change', function(){
   if(this.checked)
      currency_code.val('2')
   else
      currency_code.val('')
 })  

In your controller, you can simply assign the values

 def create
  // other codes //
   @obj.currency_code = params[:currency_code]
 end

Upvotes: 1

ayush lodhi
ayush lodhi

Reputation: 407

If you want to validate input on model level you should store the currency? in the database.

Still let say for some unexplained reasons you don't want to store currency? in you database(which I won't suggest you in any case). You can define a method in model.

def set_currency_if_required is_currency_required
   self.currency_code = nil unless is_currency_required
end

in controller

def create
  model = Model.new(data_params)
  model.set_currency_if_required(params[:data][:currency].to_bool)
  model.save
end
...
def data_params
  parameters = params.require(:data).permit(
    :currency_code
  )
end

this way you will have better readability and a clear idea about whats going on with the code.

Upvotes: 0

Related Questions