Question: SystemStackError (stack level too deep) when jQuery ajax post

Question

SystemStackError (stack level too deep) when jQuery ajax post

Answers 1
Added at 2017-01-02 03:01
Tags
Question

I have a form and when user enters some value in a text field i want to autofill other fields, but it keeps returning SystemStackError (stack level too deep). This are the files:

routes.rb

scope :places, controller: :places, as: :places do
    post :postcode, action: :postcode, as: :postcode
end

form.html.erb

<form>
    <input type="text" class="input_postcode">
    <input type="text" class="input_state">
</form>

main.js

$(document).on('change', ".input_postcode", function(e) {
    e.stopPropagation();
    e.preventDefault();
    var postcode = $(this).val();
    $.post( 'places/postcode', { postcode: postcode }, function(data) {
        $(".input_state").val(data.state);
        return false;
    }, 'json');
    return false;
});

places_controller.rb

def postcode
    place = Place.where(postcode: postcode).first
    state = place.state.name
    respond_to do |format|
        format.js { render json: { state: state } }
    end
end

I get this results in console:

SystemStackError (stack level too deep):
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    app/controllers/places_controller.rb:4:in `postcode'
    (keeps going the infinite loop...)

The line 4 in places_controller is the place = Place.where(postcode: postcode).first line.

I don't know what am i doing wrong. Hope someone can help me!

Answers
nr: #1 dodano: 2017-01-02 04:01

You are getting SystemStackError (stack level too deep) because your action name is postcode and your object variable name/method is also named postcode.

  place = Place.where(postcode: postcode).first

The error occurs when you pass in postcode attribute because it has the same name as the method/action.

To fix the error, rename the action and route name.

Source Show
◀ Wstecz