ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-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.
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) %>
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