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

330 Views Asked by At

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
2

There are 2 best solutions below

0
On BEST ANSWER

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 :-)

0
On

You could use enum for status attribute in task model

# app/models/task.rb

enum status: %i[not-completed completed not-started]

This will associate status value 0 to not-completed, 1 to completed, and 2 to not-started.

Now if you access task.status it will output string value only. If you need the integer value you will have to use Task.statuses['completed'].

you will also have some extra methods like not-completed?, completed? and not-started? which will return true or false depending on the value of the status attribute.

Please refer the below links for more details

https://api.rubyonrails.org/v5.2.3/classes/ActiveRecord/Enum.html https://naturaily.com/blog/ruby-on-rails-enum