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
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
Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
ReplyDeleteruby on rails training India
ruby on rails training Hyderabad