Rails 5:CoffeeScript中动态表ID访问



在索引视图中,我有一个我想动态填充ID的表。到目前为止,我尝试了:

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

控制器中的方法:

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

然后,我想访问我的咖啡本中的特定表。我这样做了:

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

但是它似乎行不通。我在页面源中看到了我的表ID: id="table_MyController"

如何正确访问我的表ID,请?谢谢!

update

索引中的表:

<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">

看来,您的咖啡文字中的 <%= raw ...%>字面意思是解释的。通过HTML数据属性将所有数据从Rails到CoffeeScript传递到CoffeeScript,而不是尝试插值。使用数据属性还减少了导轨和JavaScript代码之间的耦合。

您可以做这样的事情:

applicationController.rb

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

广告系列Scontroller.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", "$3,120"
        ],
        [
          "Garrett Winters", "Director", "Edinburgh", "8422", "2011/07/25", "$5,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属性的所有桌子上作用。


update 有关完整性,您可以通过将.erb附加到Coffeescript文件名来解析ERB标签,例如:

home.coffee.erb

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

但是,我仍然建议上面的HTML data-attributes方法的灵活性和将咖啡/javascript从铁路代码中解耦。

最新更新