How to use local variable or instance in ruby ββcode in coffeescript in haml template
I am new to rails and am facing a tricky problem trying to use a variable in a ruby ββhelper method in coffeescript in a haml template.
Here is my code in haml
:coffee
$('input#field').blur ->
input = $('input#field').val()
#{ ruby_method( input )}
ruby_helper.rb
def ruby_method (arg)
if arg
@model = Model.new(arg)
end
end
It will throw an error like below
undefined local variable or method
Also checked instance variable
:coffee
$('input#field').blur ->
@input = $('input#field').val()
#{ ruby_method( @input )}
It cannot pass it to a helper method.
How can I get javascript variable in ruby ββhelper method?
Thanks in advance!
source to share
The short answer is you can't. Ruby runs on your server, but any JavaScript (which CoffeeScript calls) that you put in your template will run in the browser.
Anything you put inside the block coffee:
must be valid CoffeeScript. As others point out in the comments, if you want Rails to do something with JS, you need Ajax.
For example, to build Model
with Ajax, set up a controller with an action create
and post
on it in JS.
See the excellent Working with JavaScript in Rails for more information .
source to share
Coffee Script and Rails' relation to the engine?
There is no connection between rails and coffee Script, and nothing in rails can be accessed in the coffee script.
What can I do?
Just create a file def.js.erb
in your view folder and write your javascript code. in this file, you can access the entire instance variable in the method.
How does it call method.js.erb?
use this:
respond_to do |format|
format.js
end
this will call method.js.erb instead of method.html.erb.
Hope it helps
source to share