Use jquery validate remote rule [Rails 5]

0

I am willing to use jquery validate to validate that the ID that is entered when creating a person is unique. My form is (I leave only the ID field):

<%= form_for @persona, :html => {id: 'form_personas'} do |form| %>  
  <%= form.label :dni, 'DNI (*)' %>
  <%= form.text_field :dni, class: "form-control", required: true %>    
<% end %>'

Jquery validate rules

<script type="text/javascript">

    $('#form_personas').validate({  
      rules: {  
        'persona[dni]': {   
              remote:    
                      {  
                        url: 'dni_unico',  
                        type: 'get',  
                        data: {  
                          dni: $('#persona[dni]').val()  
                        }    
                      }    
            }  
    });    

</script>

The method I use in the people controller is:

 def dni_unico  
   @existe_dni =  Persona.exists?(dni: params[:persona][:dni])  
      respond_to do |format|  
        format.json { render json: @existe_dni}  
      end  
 end

Routes
get 'dni_unico', to: 'personas#dni_unico', as: :dni_unico

The error I see is:
Couldn't find Persona with 'id'=dni_unico

Request parameters
{"persona"=>{"dni"=>"20156540"},
 "dni"=>"20156540",
 "id"=>"dni_unico"}  

I do not understand why you are looking for me by id and send the name of the method. Can someone give me a hand?

    
asked by Eragon 29.12.2017 в 00:05
source

2 answers

0

I assume that the error is being delivered to you by remote validation. I've never used that library, but you could try something like this:

$('#form_personas').validate({  
  rules: {  
    'persona[dni]': {   
      remote: {  
        url: 'dni_unico/' + $('#persona[dni]').val()
      }    
    }  
});    

In your routes file

get 'dni_unico/:dni', to: 'personas#dni_unico', as: :dni_unico

And on your controller:

def dni_unico  
  render json: Persona.exists?(dni: params[:dni])  
end
    
answered by 29.12.2017 в 15:45
0

The solution was the following:
Change my route to:
resources :personas do collection do get 'dni_unico' end end

And it worked. It was necessary to clarify that it is a collection

    
answered by 04.01.2018 в 20:32