0

I've got controller on the back-end, and want to have variables inside (coffee)script which send with mockup to browser - but got undifined values. what I'm doing wrong? I could see values in mockup.

contoller:

def show
    @article = Article.find(params[:id])
end

Script article.coffee.erb:

$ ->
      $('#sendComment').click ->
        id = "#{@article.id}"
        console.log(id)

in mockup:

%p
  %strong Title:
  #id
  = @article.id
%p
  %strong Title:
  = @article.title
2
  • Where and how is article.coffee.erb being loaded? Where is #sendComment? Instead of mockup tell us where are you rendering that HAML? Commented Aug 25, 2017 at 20:36
  • @Leito it's already on page when it loaded - rails added it where like script Commented Aug 25, 2017 at 20:42

2 Answers 2

2

The front-end code is parsed by browser and is not aware of the server-side code in controllers. The assets are compiled once and won't change on different requests. What you need to do is to add the article id in the HTML tag, and then fetch it in your JS code:

<%= tag.p data: { "article-id": @article.id } %>

then in JS:

$('p').click( (event) ->
  id = $(event.target).data('article-id')
  console.log(id)
)

It's not clear where is #sendComment in your view code so I changed it to p here. But the point is clear anyway.

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

2 Comments

It's look better but problem that in mockup after I used haml converter it's look like this : <p data-article-id="11"></p>
@FridmanChan That's the correct behavior. the .data() function on jquery is for getting the data attributes from the html tags: api.jquery.com/data
0

if @article is a controller variable you need to use <%= @article.id %> erb interpolation to get the value from the controller.

$ ->
      $('#sendComment').click ->
        id = "<%= @article.id %>" # instead of "#{@article.id}" which is the CoffeeScript String interpolation. 
        console.log(id)

3 Comments

Not work. if I write exactly like you send - its error : undefined method `id' for nil:NilClass . It means that @article still empty
@FridmanChan what is the url that you're using to access make sure that the article you're tying to access it's actually there in the DB.
I could see this id on mockup.100% its in DB

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.