0

In rail 3/4, exporting to csv can be done by defining method self.to_csv in model and add format.csv to respond_to in controller. A click to link_to "CSV", index_path(format: "csv") start exporting. The exporting calls the same action again and render in csv.

Our question is how a use can export current page to csv. A user may start searching, then decide to export the current page to csv (without redo the search for csv exporting). Is there a way a user can do so?

UPDATE: example of controller code for csv exporting:

  #for csv download
  respond_to do |format|
    format.html {@query = @query.page(params[:page]).per_page(30)}
    format.csv do
      send_data @query.to_csv
      @csv = true
    end
  end

Here is the example of self.to_csv in model:

def self.to_csv
      CSV.generate do |csv|
        #header array
        header = ['id', 'action', 'resource', 'brief_note', 'last_updated_by_id', 'role_definition_id', 'sql_code', 'masked_attrs', 'rank', 'created_at', 'updated_at']        
        csv << header
        all.each do |config|
          #assembly array for the row
          .....
          #inject to csv
          csv << row
        end
      end
    end

1 Answer 1

4

If your page is taking into account a search parameters (let say a @query variable) in the controller, you could simply call back the exact same controller, but asking for CSV format instead of HTML.

Let's suppose you are listing users in a /users routes, and have a search parameter such as:

/users?query=smith

You could create a link to generate:

/users.csv?query=smith

This will call back the same controller, just changing the format. This could be done using code like:

link_to "CSV", index_path(format: "csv", :query => @query)
3
  • @@Martin, how can I retrieve @query in self.to_csv when generating csv? Do I need to add a variable .to_csv as self.to_csv(query)?
    – user938363
    Apr 5, 2015 at 17:17
  • It's difficult to answer without having your controller's code (just the index method) - could you post it here?
    – Martin
    Apr 5, 2015 at 17:33
  • Just posted controller and model code. Use @query instead for convenience. Thanks.
    – user938363
    Apr 5, 2015 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.