Rails 5: Coffeescript 中的动态 table ID 访问

Rails 5: dynamic table ID access in Coffeescript

在索引视图中,我有 table 我想动态填充 ID 的地方。 到目前为止我试过这个:

id="table_<%= @controller_name %>"

控制器中的方法:

def get_controller_name
  @controller_name = self.class.name.split("::").last
end

然后我想在我的 Coffeescript 中访问特定的 Table。我是这样做的:

$ ->
  myvar = '<%= raw @controller_name.to_json %>'
  myvarAsObj = JSON.parse(myvar)
  $('#' + 'table_' + myvarAsObj).DataTable

但是它似乎不起作用。 我在 Page Source 中看到我得到了这样的 Table ID: id="table_MyController"

如何在 Coffeescript 中正确访问我的 table ID? 谢谢!

更新

Table 在索引中:

<table data-controller-name="<%= @controller_name %>" cellpadding="0" cellspacing="0" 
border="0" class="table table-striped table-bordered table-hover" width="100%" 
data-source="<%= campaign_campaigns_index_path(format: :json) %>">

咖啡脚本:

$ ->
  $('table[data-controller-name]').each ->
    $(this).DataTable
    ajax: $('table[data-controller-name]').each ->
      $(this).data('source')

页面来源:

<table data-controller-name="CampaignsController" cellpadding="0" cellspacing="0" border="0"
  class="table table-striped table-bordered table-hover" width="100%"
  data-source="/en/campaigns.json">

看起来您的 coffeescript 中的 <%= raw ...%> 是按字面解释的。通过 HTML 数据属性将任何数据从 Rails 传递到 Coffeescript,而不是尝试对其进行插值,我总是取得更大的成功。使用数据属性还可以减少 rails 和 javascript 代码之间的耦合。

你可以这样做:

ApplicationController.rb

def get_controller_name
  @controller_name = self.class.name.split("::").last
end

CampaignsController.rb

def index
  # Render your data as JSON. Example data from the DataTables site:
  render json: {
      data: [
        [
          "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", ",120"
        ],
        [
          "Garrett Winters", "Director", "Edinburgh", "8422", "2011/07/25", ",300"
        ]
      ]
    }
end

home.coffee

$ ->
  $('table[data-controller-name]').each ->
    el = $(this)

    el.DataTable {
      ajax: el.data('source')
    }

index.html.erb

<table data-controller-name="<%= controller.get_controller_name %>"
       data-source="<%= campaign_campaigns_index_path(format: 'json') %>">
   <thead>
     <tr>
         <th>Column 1</th>
         <th>Column 2</th>
     </tr>
   </thead>
   <tbody>
       <tr>
           <td>Row 1 Data 1</td>
           <td>Row 1 Data 2</td>
       </tr>
       <tr>
           <td>Row 2 Data 1</td>
           <td>Row 2 Data 2</td>
       </tr>
   </tbody>
</table>

coffeescript 将作用于任何具有 data-controller-name 属性的表。


更新 为了完整起见,您可以 parse ERB tags 通过将 .erb 附加到 Coffeescript 文件名,例如:

home.coffee.erb

$ ->
  $('#table_<%= @controller_name %>').DataTable {
    ajax: el.data('source')
  }

但是,我仍然建议使用上面的 HTML data-attributes 方法,因为它具有灵活性并且可以将 Coffee/Javascript 与 Rails 代码分离。