When I thought about making a draft function, there weren't many articles, so I decided to keep a record.
ubuntu(WSL)
Ruby 2,5.1
Rails 6.0.2
The following functions are assumed to have been created.
--Post function / details / delete / edit (Post) --Create / Details of User (User)
models/post.rb
belongs_to :user
models/user.rb
has_many :microposts, dependent: :destroy
First, add a status column to the Post model to make it a boolean type. It is possible to use interger instead of boolean. Enter the following command.
bin/rails g migration AddStatusToPost status:boolean
Edit the migration file.
migrationfile.rb
def change
add_column :microposts, :status, :boolean, default: true, null: false
end
After editing, migrate.
models/post.rb
enum status: { draft: false, published: true }
Specify the draft of the status column as false and the published of the status column as true.
Get the id of user with @ user
.
users_controller.rb
#For draft
def confirm
@user = User.find(params[:user_id])
@microposts = @user.microposts.draft.page(params[:page])
end
#For publication
def show
@user = User.find(params[:id])
@microposts = @user.microposts.published.page(params[:page])
end
If you add collection
, the URL will not have an id.
routes.rb
resources :users do
get 'confirm'
end
I have extracted only the relevant parts.
view/users/show.html.slim
//User details screen
= link_to "Post list", @user
= link_to "favorite", user_likes_path(current_user)
= link_to "Draft list", user_confirm_path(current_user)
//View my post
- if @microposts.present?
= render "microposts/list", microposts: @microposts
- else
h4 No posts
Please write the draft list according to your preference.
view/users/confirm.html.slim
h4 draft list
table.table.table-hover
thead.thead-default
tr
th = Micropost.human_attribute_name(:title)
th = Micropost.human_attribute_name(:content)
th = Micropost.human_attribute_name(:created_at)
th
tbody
- @microposts.each do |micropost|
tr
td = link_to micropost.title, micropost
td = link_to micropost.content, micropost
td
The contents of ʻicroposts / list` are the same as above.
If you make a mistake, please make an edit request or comment.
-Now you can save draft and public articles using Rails enum
Recommended Posts