1

Short story:

I am trying to pass a variable from JavaScript (specifically, jQuery) as a parameter in an embedded ruby method.

Long story:

It all begins with a function. In summary, I have date picker built via jQuery UI.

#my_budget.html.erb
<h1 class="text-center">Your Budget</h1>
<h4 class="text-center">Select Month to View</h4>
<input style="width:200px" name="startDate" id="startDate" class="date-picker form-control" placeholder="Select Month"/>

<br>
<br>

<script type="text/javascript">
  function setDateRange() {
    $('.date-picker').change(function() {
     var date = $(this).val(); 
     return date
    });
  }

  $(document).ready(setDateRange);
</script>

Further down the road, I have embedded ruby attempting to make a call to said variable (date). This value is passed via MM/YYYY format.

#my_budget.html.erb
<td class="section-value"><%= number_to_currency(@user.total_income(date)) %></td>

Here's a peek at my model.

#user.rb
# General Income
  def total_income(current_month)
    total_value = Transaction.joins(:user).where("transactions.sub_category" => '11').where("created_at = ?", current_month).sum(:amount)
    total_value
  end

For fairly obvious reasons, this does not work.

I am a junior developer in Rails and am still learning when to use Ruby versus JS for certain functions.

What is the best way to go about passing my JS variable into my embedded Ruby? Alternatively, how can I call the input value "on change" via Ruby into my function, so when a user selects "March 2017" in the date picker, Ruby says "Hey, it changed! Let's use it!" and adjusts the value accordingly.

Thank you!

jcxswc
  • 27
  • 4
  • Sounds like a great time for a lesson on HTTP…foundational knowledge will help you get out of situations like this. – coreyward Jan 10 '17 at 21:21
  • http://stackoverflow.com/questions/32724881/is-there-a-way-to-pass-javascript-variable-into-ruby-method-in-html-erb – gwalshington Jan 10 '17 at 21:42
  • You need to understand that Ruby does not run in the browser. So there's no way for Ruby to know about the 'change' event without you sending a HTTP request to the server. From the client's perspective, there is no ERB. They only see HTML/CSS/Javascript, etc. – max pleaner Jan 10 '17 at 21:50
  • Ah! @maxple that explains my error in thinking completely. Thank you! Would best practice be to have a 'submit' button below the selected date, to then process the value via ruby and sort the results? – jcxswc Jan 10 '17 at 22:11
  • @jcxswc there's not really a single best practice here. It depends how you're building the site.I.e. does every form submission cause a page reload?(this is the easiest way). or are you using AJAX or websockets? – max pleaner Jan 10 '17 at 22:16
  • @maxple all form submissions cause page reloading! My purpose here is to pass the information to the user.rb model and display the result filtered by the month-range of transactions (as seen in the model). So, I could process the date via form submission, and reload the page with the updated query. To do this, will I need to process this input value in my model then call it in the controller, thereby passing it as a parameter? – jcxswc Jan 10 '17 at 22:30

1 Answers1

1

Simply put, Ruby runs on your server and all erb tags are evaluated by the time it reaches the client. Ex:

<%= number_to_currency(@user.total_income(date)) %>

If you attempt to change "date" with javascript you will fail because by the time javascript tries to change it, rails and your server already evaluated the method and it will return that value not the Ruby method.

Now, you have two simple options here:

  1. Write a Javascript function that does the same what your Ruby code is suppose to do.
  2. Sent an Ajax call to your server, let Rails process the request and respond with json or javascript to the client.

The first option is probably simpler and will be better for your server since it would not have to take care of extra requests.

The second option requires you to create a form and set it to remote: true. In your controller you will have to receive the content of the form, call your @user.total_income method and set the respond_to so that it return json or javascript:

@user_income = @user.total_income(params[:date)
respond_to do |format|
  format.html
  format.js
end

Then you will have to create a javascript file in your views folder and write some javascript with the info you want the user to get. Simplistically, it will look something like this:

$('#where-to-put-your-income').append('<%= j render @user_income %>');

You can read about how to use Ruby and Javascript here:

http://guides.rubyonrails.org/working_with_javascript_in_rails.html http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

Good luck, I'm also still a Junior Rails developer, let's do our best.

Alexander Luna
  • 5,261
  • 4
  • 30
  • 36