0

I'm cleaning up my code of my Rails-app. I'm using the Raty-gem for my rating system. To render a #average_rating I'm using a script-block (picked this up in some tutorial) in the specific views. But since I'm using the #average_rating in over 6 different views, I was hoping that I could do this more efficient. I already tried to use a HelperMethod for it, but i guess that it doesn't accept 'javascript'.

Script-block:

<script>
$('#average_rating').raty({
    path: '',
    readOnly: true,
    score: <%= @project.average_rating %>
});
</script>

What is the cleanest way of doing this in Rails?

2 Answers2

0

Yes there is cleaner way of defining a JavaScript block using content_for helper method provided by rails. You can define a code snippet inside a named content_for block and can be used anywhere in your views. e.g

<% content_for :rating_code do %>
  $('#average_rating').raty({
    path: '',
    readOnly: true,
    score: <%= @project.average_rating %>
  });
<% end %>

See documentation here: http://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for

Hassan Akram
  • 641
  • 6
  • 19
  • Okay, looks simple. But where do I place this block of code: in a helper-method? (it seems like it contains view-code) Or somewhere else? – Sebastian Plasschaert Nov 25 '15 at 13:31
  • You can define content for tag in `app/views/layouts/application.html.erb` file and initialize it in any of the views. The code will be only generated in which page you have yield the code like this `<%= yield(:code_tag_name) %>` – Hassan Akram Nov 25 '15 at 14:50
0

If you have a lot of data to pass to the JavaScript and you want to keep your js code in js files, you can use the Gon gem

Alexander Kobelev
  • 1,379
  • 8
  • 14