0

I have an app where a user has a portfolio that has many positions and each position has many movements. So the url for an associated movement index page for a particular position looks like: portfolio_position_movements. I have an index page with and the controller action looks like

def index
  @movements = @position.movements.all
  respond_to do |format|
    format.html
    format.json { render json: @movements}
  end
end

My ajax call in my movements.js file is this:

var loadData = function(){
            $.ajax({
              type: 'GET',
              contentType: 'application/json; charset=utf-8',
              url: ?,
              dataType: 'json',
              success: function(data){
                drawBarPlot(data);
              },
              failure: function(result){
                error();
              }
            });
          };

How can I pass in a dynamic route path so this will work with the movement index on any position object?

1 Answer 1

1

You can use erb tags in js files, for me i did it as the following:

#edit.js.erb

$modal = $('.modal'),
$modalBody = $('.modal .modal-body'),
$modalHeading = $('.modal .modal-heading');
$modalHeading.html("Edit <%= @student.full_name.titleize %>'s information");
$modalBody.html("<%= escape_javascript(render 'edit_student') %>");
$modal.modal();

Note: the file extension is .js.erb so rails can process it. I was calling a modal form and the edit method in students_controller.rb was:

 def edit
    @student = Student.find(params[:id])
    respond_to do |format|
      format.html # edit.html.erb
      format.js # edit.js.erb
      format.json { render json: @student }
    end
  end

Edit:

You can embed the JS code inside html.erb and use rails routes like:

<script>
var loadData = function(){
            $.ajax({
              type: 'GET',
              contentType: 'application/json; charset=utf-8',
              url: <%= my_ajax_path %>,
              dataType: 'json',
              success: function(data){
                drawBarPlot(data);
              },
              failure: function(result){
                error();
              }
            });
          };
</script>

What is my_ajax_path?

Is a rails route defined in routes.rb for example i need a list of all available sections that students can apply to using ajax so i did the following:

1- defined a method in students_controllers.rb like this one:

  def available_sections
    batch_id =  (params[:batch_id].nil? || params[:batch_id].empty?) ? 0 : params[:batch_id].to_i

    if batch_id == 0
      @sections = [].insert(0, "Select Section")
    else
      batch = Batch.find(params[:batch_id])
      # map to name and id for use in our options_for_select
      @sections = batch.sections.map{|a| [a.section_name, a.id]}
    end
  end

2- added a route to it in routes.rb

resources :students do
  collection do
    get :available_sections
    post :create_multiple
  end
end

3- Inside new.html.erb:

<script type="text/javascript">
$(document).ready(function() {
    $('.student_section_id').hide();
    $('#student_batch').change(function() {
        $.ajax({
            url: "/students/available_sections",
            data: {
                batch_id : $('#student_batch').val()
            },
            dataType: "script",
            success: function () {
                if (+$('#student_batch').val() > 0)
                {
                    $('.student_section_id').fadeIn();
                }
                else
                {
                    $('.student_section_id').fadeOut();
                }
            } 
        });
    });
});
</script>

Forget about that messy code :D as it was my first steps but you get the point, and for this line url: "/students/available_sections" it should be using rails routes you can get it by calling rails routes from the command line to get a list of all your application routes

Sign up to request clarification or add additional context in comments.

3 Comments

I have a movements.js file. How can I get the value in that file? Or do you just place script tags in the html file?
Where do you define my_ajax_path?
my_ajax_path is a route which should be defined in routes.rb

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.