0

My form has options to select a section based on previous selections. Once the section is selected I need to count and show how many Questions belong to the section.

I am trying to count the questions but cannot figure out the syntax. Here I am trying to update a @count variable every time a section is selected. Then assign the @count value to a hidden field which my table uses to add a row.

How do you do this query? The $('#question_section') is wrong syntax.

$('#question_section').change(function() {
            <% @count = Question.where(section: $('#question_section')).count %>
            $('input[name="question_count"]').val(<% @count %>);
   });
1
  • please check the idea and better way to solve this problem. Thanks. Commented Nov 4, 2014 at 18:41

3 Answers 3

1

Need more information. Basically the code of your view. I don't think you need to write any rails query inside your jquery. This shoud be pretty easy.

So far I assumed, from your form user will receive choices for section to questions. So the steps should be following.

You will bind the change event on your select httm input.

$("#question_section").on(function(){
    var value = $(this).value() // get whats the section value/text
})

Now get added an action on your controller where you will count the question with the query. So for this you will need to do to things. Registrar the action in route something like following:

resources :questions do  # I assume there is a questions resource 
    get :count, on: :collection
end

Now this will give you a url as route to that action. Now lets get back to javascript part again.

    $("#question_section").on(function(){
    var value = $(this).val() // get whats the section value/text
    $.ajax({
           url: '/questions/count.js', // you can skip the format here
           data: {section: value}
           success: function(data){
                  $('input[name="question_count"]').val(data)
           }
    })
    })

So now we are ready with the script. Now lets move to controller.

def count
    number_of_questions = Question.select("DISTINCT(section)").where(section: params[:section]).count
    render :js => number_of_questions

end

Well this is the steps you may follow. Direct query in the view layer is not acceptable. Responsibility centric design doesn't encourage that. I hope I can give some hints with my approach.

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

1 Comment

Let me if you need any help. @DDDD anytime :)
0

The problem with this code is that everything between <% and %> is evaluated only once on the server. The rest of the code is evaluated afterwards as JavaScript in the browser. You'll have to expose this query in some controller:

Question.where(section: $('#question_section')).count

...and then ask the server for data every time the user changes the select:

$('#question_section').change(function() {
  var url = "/path/to/your/service/" + $(this).val();
  $.get(url, function(data) {
    $('input[name="question_count"]').val(data.count);
  }
});

1 Comment

What is the path to your service? The controller method? How would you write the path to a controller method in JS?
0

I am assumming that section attribute is a string or integer. Again assuming that the HTML element with the id='question_select' is a <select> tag, the jQuery line of code $('#question_section') will return a jQuery object (essentially a javascript object). And in the ActiveRecord Query Interface line of code Question.where(section: $('#question_select')) you have inserted the jQuery object when it will be expecting a String or Fixnum (integer in ruby) object depending on the datatype of section. That is the reason it is giving an error.

To fix this you can do the following ->

  1. in javascript

    <script type="javascript">
      $(document).ready(function(){
        $('#question').on('change',function(){
          var url = window.locatio.origin + '/questions/get_number_of_questions'
          var data = { section : $('#question_select').val() };
          $.ajax({
            type: 'POST',
            url: url,
            data: data,
            success: function(result){
              $('input[name="question_count"]').val(result[count]);
            }
          });
        });
      });
    
  2. In your routes.rb file define a route for an action get_number_of_questions of type post under questions

    resources :questions do
      collection do
        post :get_number_of_questions
      end
    end
    
  3. Finally in your questions_controller.rb file define the action

    class QuestionsController < ApplicationController
      ...
    
      def get_number_of_questions
        count = Question.where(section: params[:section]).count
        render :json { count: count }
      end
    
      ...
    end
    

Remember to keep your javascript and rails or ruby code as separate as possible. That is one of the best practices followed under RoR convention. Hope this helps Thank you.

Comments

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.