0

This is more of an architecture/functional question for Rails. I have a search function which sends the criteria to the model where the query resides. The search works. Now I have a CSV export link <%= link_to "CSV", contacts_path(format: "csv") %> in my view file which points to localhost/books.csv.

The export didn't work without my search parameters (so localhost/book.csv?book_name=foo works as expected). What I do in send_data is I pass the @books object to the .to_csv function inside my model, and it becomes nil without passing the parameter also. Pls see code below.

My controller:

def index
  @books = Book.search(params[:search])
  respond_to do |format|
    format.html
    format.csv { send_data Book.to_csv(@books) }
end

My model:

def self.search(criteria)
 find(:all, :conditions => ['book_name LIKE ?', "%#{criteria}%"])
end

def self.to_csv(search_results)
  CSV.generate do |csv|
   csv << column_names
   search_results.each do |contact|
     csv << contact.attributes.values_at(*column_names)
   end
  end
end

I like to understand why. The current setup seems to be making another request to the server in order to generate the CSV file, and that's why it requires the parameters in localhost/books.csv request. Is this correct?

Now, if instead I put the query inside the controller like below, the CSV request works as expected (so I just click the link and receive the file).

 def index
   @books = Book.find(:all, :conditions => ['book_name LIKE ?', "%#{criteria}%"])       respond_to do |format|
   format.html
   format.csv { send_data Book.to_csv(@books) }
 end

I love to keep the query inside the model for the sake of organization, so would be awesome if you guys can point me to the right direction. Thanks!

1 Answer 1

1

I would suggest that you change your link to something like this:

<%= link_to "CSV", contacts_path(params.merge(format: "csv")) %>

This will pass down the current search parameters plus the new option for the format to be CSV. Then you can continue to keep the search method inside the model in the way that you had originally written it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.