【问题标题】:Ruby on Rails How to inject values from controller inside coffeescriptRuby on Rails 如何从咖啡脚本中的控制器注入值
【发布时间】:2018-02-03 22:11:10
【问题描述】:

我在后端有控制器,并且希望在(咖啡)脚本中包含变量,这些变量与模型一起发送到浏览器 - 但得到了未定义的值。我做错了什么?我可以在模型中看到值。

控制器:

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

脚本 article.coffee.erb:

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

在模型中:

%p
  %strong Title:
  #id
  = @article.id
%p
  %strong Title:
  = @article.title

【问题讨论】:

  • article.coffee.erb 在哪里以及如何加载? #sendComment 在哪里?而不是 mockup 告诉我们你在哪里渲染 HAML?
  • @Leito 它在加载时已经在页面上 - rails 将它添加到脚本中

标签: javascript ruby-on-rails ruby coffeescript


【解决方案1】:

前端代码由浏览器解析,不知道控制器中的服务器端代码。资产只编译一次,不会因不同的请求而改变。你需要做的是在 HTML 标签中添加文章 id,然后在你的 JS 代码中获取它:

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

然后在 JS 中:

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

不清楚您的视图代码中#sendComment 在哪里,所以我在此处将其更改为p。但无论如何,这一点很清楚。

【讨论】:

  • 看起来更好,但问题是,在我使用 haml 转换器后的模型中,它看起来像这样:

  • @FridmanChan 这是正确的行为。 jquery 上的 .data() 函数用于从 html 标签中获取 data 属性:api.jquery.com/data
【解决方案2】:

如果@article 是控制器变量,您需要使用&lt;%= @article.id %&gt; erb 插值从控制器获取值。

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

【讨论】:

  • 不工作。如果我写的和你发送的完全一样 - 它的错误:未定义的方法 `id' for nil:NilClass 。这意味着@article 仍然是空的
  • @FridmanChan 您用来访问的网址是什么,确保您要访问的文章确实在数据库中。
  • 我可以在模型上看到这个 id。100% 它在数据库中
猜你喜欢
  • 2012-11-27
  • 2019-05-02
  • 2013-01-09
  • 1970-01-01
  • 2019-05-05
  • 2014-12-18
  • 2018-11-06
  • 1970-01-01
  • 2011-11-08
相关资源
最近更新 更多