Rails - How to export nested resources to CSV in Rails?
<p>I am trying to export some data to CSV in Rails 4. I have two models: Excursions and Inscriptions. One excursion has many inscriptions and one inscription belongs to one excursion. </p>

<p>I have my nested routes defined this way:</p>

<pre><code>  resources :excursions do
    resources :inscriptions
    get 'exportcsv' =&gt; 'excursions#download'
  end
</code></pre>

<p>So the behavior I am trying to achieve is: when I visit the route <em>/excursions/1/exportcsv</em>, a CSV will be downloaded to my computer and it will contain all the inscriptions with excursion_id = 1 in CSV format.</p>

<p>In my excursion model I have defined self.to_csv:</p>

<pre><code>  def self.to_csv(options = {})
    CSV.generate(options) do |csv|
      csv &lt;&lt; column_names
      self.inscriptions.each do |inscription|
        csv &lt;&lt; inscription.attributes.values_at(*column_names)
      end
    end
  end
</code></pre>

<p>And my excursion controller's method download:</p>

<pre><code>  def download
    @excursion = Excursion.find(params[:id])
    respond_to do |format|
      format.html
      format.csv { send_data @excursion.to_csv }
    end
  end
</code></pre>

<p>EDIT: When I go to a route like: /excursions/:id/exportcsv the server is throwing an ActiveRecord::RecordNotFound error. This error is easy to solve, but if I solve the RecordNotFound I get an ActionController::UnknownFormat in this line:</p>

<pre><code>  def download
    @excursion = Excursion.find(params[:id])
    respond_to do |format|  ########THIS LINE
      format.html
      format.csv { send_data @excursion.to_csv }
    end
  end
</code></pre>

<p>What I am doing wrong? Maybe all this approach is not correct...</p>