1

I'm working on a project in rails and recently watched this great gorails.com episode on exporting data as CSV (https://gorails.com/episodes/export-to-csv). I can get it to work, but I really want to get the absolute url of each of the "tasks" so in the CSV export it would show in each row as a 4th column the link to the "task" eg: "localhost:3000/tasks/1" "localhost:3000/tasks/2" etc. Something like "task_url" as the column header

I haven't found any resource online that helps with this. Any thoughts on how to do this in the most efficient way? Thank you for the help! Here is the working code:

def self.to_csv
    attributes = %w{id task_name task_description}
    CSV.generate(headers: true) do |csv|
    csv << attributes
        all.each do |task|
          csv << attributes.map{ |attr| task.send(attr) }
        end
    end
end

And I would like to do something like this (emphasis added around task_url):

def self.to_csv
    #need to declare what task_url is here
    attributes = %w{id task_name task_description **task_url**}
    CSV.generate(headers: true) do |csv|
    csv << attributes
        all.each do |task|
          csv << attributes.map{ |attr| task.send(attr) }
        end
    end
end
Taylor
  • 45
  • 6

1 Answers1

0

You could update your Task model with a #task_url instance method so that calling send on the task instances works. Then next implement the #task_url method with the necessary logic to the build and return the appropriate link for the individual task object. Something like:

class Task
  include Rails.application.routes.url_helpers

  ...

  def self.to_csv
    attributes = %w{id task_name task_description task_link}
    CSV.generate(headers: true) do |csv|
      csv << attributes
      all.each do |task|
        csv << attributes.map{ |attr| task.send(attr) }
      end
    end
  end

  def task_link
    task_url(self)
  end
end

In this example, the links are constructed using the rails routes helpers. And to access them, we'll need to the include the #url_helpers module since they are not available (by default) in the model layer.

Notice that in the example, the method is called #task_link; the assumption being that the route helper method is already named #task_url and so we avoid overriding it.

  • Thank you for your help! I really appreciate it. I've implemented your solution and am getting the following error, `Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true` do you have any ideas? – Taylor Sep 20 '18 at 21:20
  • And in my development.rb file I've already set my default hosts: `config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } ` – Taylor Sep 20 '18 at 21:48
  • 1
    NM, got it work myself, I had to declare the following in my development.rb file, and this worked! Thanks! `Rails.application.routes.default_url_options[:host] = 'localhost:3000'` – Taylor Sep 20 '18 at 21:51