添加样式到从Rails控制器输出的format.html

时间:2013-06-20 14:24:36

标签: ruby-on-rails

reports.rb

def method
  if self.name == "Maintenance History"
    'maintenance_history'
  elsif self.name == "Outstanding Maintenance"
    'outstanding_maintenance'
  elsif self.name == "Idle Time Report"
   'idle_time_report'
  end
end

def maintenance_history
  maintenance_history.where(....)
end

def outstanding_maintenance
  outstanding_maintenance.where(....)
end

def idle_time_report
  idle_time_report.where(....)
end

reports_controller

  def show
    @report = Report.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb

show.html.haml

= render @report.method, :report => @report

我想在视图中使用以下标记%table.table.datatable#datatable

格式化html表格

此:

%table.table.datatable#datatable
  = render @report.method, :report => @report

不起作用......

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,那就是根据报告,不同的表需要不同的样式。就像您在控制器中使用报告的名称来确定范围一样,您可以在视图中使用报告的某些属性来向HTML添加类或其他标识属性。

作为一个简单示例,您可以像您的method控制器方法一样为视图完全创建一个帮助器,如:

# some helper for the reports
module ReportsHelper

  # the `method` method from your controller, migrated to a helper
  def report_table_class(report)
    if report.name == "Maintenance History"
      'maintenance_history'
    elsif report.name == "Outstanding Maintenance"
      'outstanding_maintenance'
    elsif report.name == "Idle Time Report"
      'idle_time_report'
    end
  end
end

然后在您的视图中,您可以使用它来划分表格或父元素,您可以将其用作样式选择器的目标:

%table#datatable{:class => ['table', 'datatable', report_table_class(@report)]}

最后在你的CSS中:

table.maintenance_history {
  // style accordingly
}

table.idle_time_report {
  // style accordingly
}