Rails export to CSV

300 Views Asked by At

I am trying to export my data to CSV file n allow it to be downloaded. Instead of the foregin key i want to fetch the name of that data from the related model. But i am still getting the foreign key.

//Controller
@missions = Mission.where({:status => 1}).order(:name)
    respond_to do |format|
      format.csv { render text: @missions.to_csv }
    end

// Model
def self.to_csv
    CSV.generate do |csv|
      csv << column_names
      all.each do |mission|
        csv << mission.attributes.values_at(*column_names)
      end
    end
  end

Is there a way to refer the region_id foreign key to its regions.name

1

There are 1 best solutions below

3
On BEST ANSWER

If you have a has_many relationship setup correctly, you will be able to access the name of a mission's first region using:

mission.regions.first.name

or outside your loop, you could return the region name of the first Mission using:

Mission.first.regions.first.name

If each mission is only supposed to have one region, you may want to change has_many to has_one. In this case you can drop the plural regions and replace it with region like below:

Mission.first.region.name

After this is setup, the following tutorial should help you with the rest:

https://www.lockyy.com/posts/rails-4/exporting-csv-files-in-rails