0

Well, I know that's a common question and found a lot of advice how to do it but it doesn't work for me and I can't understand what's the matter.

index.html.slim

- books.each do |book|
  .row class = "review_form" id = book.id
    .panel
      == render 'reviews/form', review: review, book: book

book.js.coffee

$('.row.review_form').hide()
  $('#new_review_button').on "click", ->
    $('.row.review_form#<%= book.id %>').show()
    $('#new_review_button').hide()
  $('#cancel_review').on "click", ->
    $(".row.review_form#<%= book.id %>").hide()
    $('#new_review_button').show()

According to instructions if you want to use ruby code in javascript you should use <%= ruby code %> as i'm doing here $('.row.review_form#<%= book.id %>').show() but nothing happens. It seems like when i write <%= in brackets it changes into one string and js doesn't understand it's a selector with ruby code. What am I doing wrong? Please, help, I'm totally confused! ><

Jakov
  • 151
  • 13
  • What exactly is the error here? – Sergio Tulentsev Jun 17 '16 at 11:56
  • @Sergio No error, just nothing happens. If I open console and see js there is just $(".row.review_form#<%= book.id %>").hide(); not $(".row.review_form#1").hide(); for instance. And rubymine highlights this line as if it was just a string but not selector when i start writing <%= – Jakov Jun 17 '16 at 12:20
  • Where do you render your coffee file then? Keep in mind that `book` exists only within that `each` block. – Sergio Tulentsev Jun 17 '16 at 12:41
  • But isn't Ruby server-side and Coffeescript (javascript) client-side? How could these two worlds possibly interact? – Jeremy Thille Jun 17 '16 at 13:10
  • I think you need double quotes and `#{}`. `$(".row.review_form##{book.id}").show()`. [source](https://coffeescript-cookbook.github.io/chapters/strings/interpolation) – Petr Gazarov Jun 17 '16 at 13:28

1 Answers1

1

In your case you dont have a rails object in your coffee script file. You can rename your file to book.js.coffee.erb to execute <%= %># erb tags. Otherwise it will be considered as a string only. Refer to this answer for more details. Hope it works :-)

Community
  • 1
  • 1
noman tayyab
  • 355
  • 3
  • 14