简体   繁体   English

如何在haml模板中的coffeescript中的ruby代码中使用局部变量或实例变量

[英]How to use local or instance variable in ruby code in coffeescript in haml template

I'm newer of rails and facing complex issue trying to use variable in ruby helper method in coffeescript in haml template. 我是Rails的新手,面临复杂的问题,试图在haml模板中的coffeescript中的ruby helper方法中使用变量。

Here is my code in haml 这是我在haml中的代码

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

ruby_helper.rb 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? 如何在ruby helper方法中获取javascript变量?

Thanks in advance! 提前致谢!

Coffee Script and Rails engine Relation? Coffee Script和Rails引擎有关系吗?

There is no relation between rails and coffee script and nothing in rails can be accessed in coffee script. rails和coffee脚本之间没有关系,并且在coffee script中无法访问rails中的任何内容。

What can I do then ? 那我该怎么办?

Just create def.js.erb file in your view folder and write your javascript code. 只需在您的视图文件夹中创建def.js.erb文件并编写JavaScript代码即可。 in this file you can access all instance variable in method. 在此文件中,您可以访问方法中的所有实例变量。

How does it calls method.js.erb ? 它如何调用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. 这将调用method.js.erb文件而不是method.html.erb文件。

Hope It helps 希望能帮助到你

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. Ruby在您的服务器上运行,但是您放置在模板中的任何JavaScript(CoffeeScript发出)都将在浏览器中运行。

Anything you put inside a coffee: block must be valid CoffeeScript. 您在coffee:块中放入的任何东西都必须是有效的CoffeeScript。 As others have pointed out in comments, if you want Rails to do something via JS, you need Ajax. 正如其他人在评论中指出的那样,如果您希望Rails通过JS进行操作,则需要Ajax。

For example, to create a Model with Ajax, set up a controller with a create action and post to it in JS. 例如,要使用Ajax创建Model ,请使用create动作设置控制器并将其post到JS中。

For more details, see the excellent Working with JavaScript in Rails tutorial. 有关更多详细信息,请参见出色的在Rails中使用JavaScript教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM