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?
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