[Ruby on Rails] CSV output function

Target

CSV.gif

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)

The post model has title and body columns The user model has an N: 1 relationship.

First, write the completed code, and then write the supplementary code.

Completion code

Editing controller

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  require 'csv'

  def new
    @post = Post.new
    @posts = Post.all
    respond_to do |format|
      format.html
      format.csv do |csv|
        send_posts_csv(@posts)
      end
    end
  end

  private
  def send_posts_csv(posts)
    csv_data = CSV.generate do |csv|
      column_names = %w(Name of contributor Title Body)
      csv << column_names
      posts.each do |post|
        column_values = [
          post.user.name,
          post.title,
          post.body,
        ]
        csv << column_values
      end
    end
    send_data(csv_data, filename: "Post list.csv")
  end
end

view

erb:app/views/posts/new.html.erb


<%= link_to "Output with csv",new_post_path(format: :csv) %>

Supplementary code

controller

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  require 'csv' #← Be careful because it is easy to forget

  def new
    @post = Post.new
    @posts = Post.all
    # respond_to is a method that performs processing according to the request.
    #Normally, html is requested, so the process is not described.
    #view link_Since format is specified as csv with to,
    #Press the link to send_posts_csv(@posts)Is processed.
    respond_to do |format|
      format.html
      format.csv do |csv|
        send_posts_csv(@posts)
      end
    end
  end

  private
  def send_posts_csv(posts)
    # CSV.generate is a type of CSV library that automatically converts the target data into CSV format.
    csv_data = CSV.generate do |csv|
      # %w()Returns an array separated by whitespace
      column_names = %w(Name of contributor Title Body)
      # csv << column_names defines the names that go into the columns of the table.
      csv << column_names
      # column_Defines the column values to assign to values.
      posts.each do |post|
        column_values = [
          post.user.name,
          post.title,
          post.body,
				]
      # csv << column_valuesh defines the values that go into the rows of the table.
        csv << column_values
      end
    end
    #Defines the filename of the csv output.
    send_data(csv_data, filename: "Post list.csv")
  end
end

view

erb:app/views/posts/new.html.erb


<!--Specify format as csv and respond to controller_Execute to processing-->
<%= link_to "Output with csv",new_post_path(format: :csv) %>

Recommended Posts

[Ruby on Rails] CSV output function
[Ruby on Rails] Introduced paging function
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function
[Ruby on Rails] Search function (not selected)
[Rails] Addition of Ruby On Rails comment function
[Ruby on Rails] Follow function implementation: Bidirectional
[Ruby on rails] Implementation of like function
[Ruby on Rails] Logical deletion (withdrawal function)
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
Validation settings for Ruby on Rails login function
Implementation of Ruby on Rails login function (Session)
Ruby on Rails Email automatic sending function implementation
[Ruby on Rails] Post editing function (update, delete)
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.05
Ruby on rails learning record -2020.10.09
Ruby on Rails config configuration
[Ruby on Rails] about has_secure_password
Commentary on partial! --Ruby on Rails
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
Ruby on rails learning record -2020.10.06
Output Rails Routes as csv
Ruby on Rails validation summary
Ruby on Rails Basic Memorandum
Ruby on Rails <2021> Implementation of simple login function (form_with)
[Ruby on Rails] Asynchronous communication of posting function, ajax
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] Posting score ranking function (whole display)
[Ruby on Rails] Implementation of tagging function/tag filtering function
[Ruby on Rails] Post image preview function in refile
[Ruby on Rails] Search function (model, method selection formula)
Ruby on Rails Overview (Beginner Summary)
[Rails] Implementation of CSV import function
[Ruby on Rails] Read try (: [],: key)
[Ruby on Rails] yarn install --check-files
Ruby on Rails variable, constant summary
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
Ruby on Rails Email automatic sending function setting (using gmail)
[Ruby on Rails] Bookmark (favorite registration, like) function: One direction
Basic knowledge of Ruby on Rails
Progate Ruby on Rails5 Looking Back
How to use Ruby on Rails
[Rails] Implementation of CSV export function
[Ruby on Rails] Add / Remove Columns
(Ruby on Rails6) "Erase" posted content
A note about the seed function of Ruby on Rails
Ruby on Rails 6.0 environment construction memo
[Ruby on Rails] What is Bcrypt?
[Ruby on Rails] Confirmation page creation
[Ruby on Rails] Implement login function by add_token_to_users with API
Ruby On Rails devise routing conflict
Implement CSV download function in Rails
[Ruby on Rails] Convenient helper method
[Ruby on Rails] Stop "looping until ..."