Search code examples
jqueryruby-on-railsajaxhandsontable

rails with ajax param url: nested routes


I tried to find a solution but no problem looks like mine.

I have a nested resource "students" :

  resources :grades do
    resources :students
  end

Added : Controller code

students_controller.rb

before_action :set_grade

 def set_grade
    @grade = Grade.find(params[:grade_id])
  end

  def mass_input

 #use this to create the inserts (to_do) 
    datos = JSON.parse(params[:form_data])
  end

And I'm creating a massive input for students using Handsontable. My problem is I dont know how to pass the grade id (or if I need to pass it) in coffee code.

I tried with this new routes (if I dont create GET route throws error even selecting POST in the ajax part.

  get 'students/mass_input', to: 'students#mass_input'
  post 'students/mass_input', to: 'students#mass_input', as: 'mass_input'

coffee button code

  $('#stu_mass_input').on 'click', (e) ->
    form_data = { 
      mass_students: mass_students.getData(), 
    }
    $.ajax
      method: 'POST',
      data: { form_data: JSON.stringify(form_data)},
      url: '/students/mass_input'

I get the error Couldn't find Grade with 'id'= (expectable, im not giving the grade id in the URL)

I tried several ways of nesting this mass_input routes but I get the error "No student with 'id = mass_input' "

thanks guys

edit : Button is INSIDE a grade, so I have to pass the current url grade id for this mass students input


Solution

  • Your code is failing because your before filter set_grade is expecting a parameter grade_id. You can pass this as a query parameter in the url to which you send the ajax request.

    Alternatively, if your mass creation does not actually require grade to be present, you can skip the before filter for this action:

    before_action :set_grade, except: [:mass_input]
    

    Assuming you have the grade_id in the parent page, you can pass it to javascript using a generated script tag:

    In action:

    @grade_id = params[:id] 
    

    In your erb template:

    <script>
      REGISTRY = { grade_id: "<%= @grade_id %>" }
    </script>
    

    In coffee, should be included after the script tag above:

      $('#stu_mass_input').on 'click', (e) ->
        form_data = { 
          mass_students: mass_students.getData(), 
        }
        $.ajax
          method: 'POST',
          data: { form_data: JSON.stringify(form_data)},
          url: "/students/mass_input?grade_id=#{REGISTRY.grade_id}"