How to use local or instance variable in ruby code

2020-05-09 07:20发布

问题:

I'm newer of rails and facing complex issue trying to use variable in ruby helper method in coffeescript in 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

This lead a error as below

undefined local variable or method

Also tried instance variable

:coffee
  $('input#field').blur ->
    @input = $('input#field').val()
    #{ ruby_method( @input )}

This can not pass it to helper method.

How can I get javascript variable in ruby helper method?

Thanks in advance!

回答1:

Coffee Script and Rails engine Relation?

There is no relation between rails and coffee script and nothing in rails can be accessed in coffee script.

What can I do then ?

Just create def.js.erb file in your view folder and write your javascript code. in this file you can access all instance variable in method.

How does it calls method.js.erb ?

use this:

respond_to do |format|
  format.js
end

this will call method.js.erb file instead of method.html.erb file.

Hope It helps



回答2:

The short answer is, you can't. Ruby runs on your server, but any JavaScript (which CoffeeScript emits) you put in your template will run in the browser.

Anything you put inside a coffee: block must be valid CoffeeScript. As others have pointed out in comments, if you want Rails to do something via JS, you need Ajax.

For example, to create a Model with Ajax, set up a controller with a create action and post to it in JS.

For more details, see the excellent Working with JavaScript in Rails tutorial.