ruby-on-railsexcelruby-on-rails-5axlsx

how to check condition while exporting excel in rails with Axlsx gem


projecthas many task. task has attribute status with integer field 0,1 and 2 now i want to print not-completed for 0 , completed for 1 and not-started for 2.

currently i am able to print integer in place of text. i tried if condition but got syntax error

download.xlsx.axlsx

@project.tasks.each do |task|
  sheet.add_row [task.task_name, task.planned_end_date, task.status]
end

Solution

  • You can write an instance method for task object which will return desired status string depending of status value.

    # app/models/task.rb
        
    def display_status
      case status
      when 0
        "not-completed"
      when 1
        "completed"
      when 2
        "not-started"
      else
        ""
      end
    end
    

    After that use this method in your .xlsx view template.

    # download.xlsx.axlsx
    
    @project.tasks.each do |task|
      sheet.add_row [task.task_name, task.planned_end_date, task.display_status]
    end
    

    Hope this will work for you. Thanks :-)