Export custom fields in csv file in ruby on rails

  <%= link_to "Export Recipes CSV", download_recipes_path(format: "csv") %>

In Controller:-
 def download
    @recipes = Recipe.order(:name)   
     send_data @recipes.as_csv ,:filename => 'recipes'
  end

In Model:-

 #For Specific fields
  def self.as_csv
    CSV.generate do |csv|
      csv << [ "Name", "serving_size", "recipe_type", "ingredients", "method", "nutritional_analysis","trainer_id", "recipetags_ids", "description"] ## Header values of CSV
      all.each do |recipe|       
        csv << [recipe.name, recipe.serving_size, recipe.recipe_type, recipe.ingredients, recipe.method, recipe.nutritional_analysis, recipe.trainer_id, recipe.recipetaggings.collect(&:recipetag_id).join(''), recipe.description] ##Row values of CSV
      end
    end
  end

    # This will download all the fields of recipe
   def self.as_csv
     CSV.generate do |csv|
       csv << column_names
       all.each do |item|
         csv << item.attributes.values_at(*column_names)
       end
     end
   end

Comments

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete

Post a Comment

Popular Posts

How to pass hash in Postman

nginx: unrecognized service

Reading Excel Sheets using "Roo" gem in ruby on rails

Bootstrap Select Picker append add new item if search not exist

Add CORS to Nginx on AWS Elastic Beanstalk

Enable gzip compression on Elastic Beanstalk with nginx

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Get video duration by URL in Ruby on Rails

site-enables nginx setting in ruby in rails