Skip to content

Commit d93b963

Browse files
committed
a working solution
1 parent 903bec3 commit d93b963

3 files changed

Lines changed: 29 additions & 8 deletions

File tree

app/controllers/posts_controller.rb

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,31 @@ def edit
2323
def create
2424
@post = Post.new(post_params)
2525

26-
if @post.save
27-
redirect_to @post, notice: "Post was successfully created."
26+
if params[:publish]
27+
if @post.publish
28+
redirect_to @post, notice: "Post published"
29+
else
30+
render :new, status: :unprocessable_entity
31+
end
2832
else
29-
render :new, status: :unprocessable_entity
33+
@post.save
34+
redirect_to @post, notice: "Draft saved"
3035
end
3136
end
3237

3338
# PATCH/PUT /posts/1 or /posts/1.json
3439
def update
35-
if @post.update(post_params)
36-
redirect_to @post, notice: "Post was successfully updated.", status: :see_other
40+
@post.assign_attributes(post_params)
41+
42+
if params[:publish]
43+
if @post.publish
44+
redirect_to @post, notice: "Post published"
45+
else
46+
render :edit, status: :unprocessable_entity
47+
end
3748
else
38-
render :edit, status: :unprocessable_entity
49+
@post.save
50+
redirect_to @post, notice: "Draft updated"
3951
end
4052
end
4153

app/models/post.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,7 @@
11
class Post < ApplicationRecord
2+
validates :title, :body, presence: true, on: :publish
3+
4+
def publish
5+
save if valid?(:publish)
6+
end
27
end

app/views/posts/_form.html.erb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
<%= form_with(model: post) do |form| %>
22
<% if post.errors.any? %>
33
<div style="color: red">
4-
<h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
4+
<h2>
5+
<%= pluralize(post.errors.count, "error") %> prohibited this post from
6+
being saved:
7+
</h2>
58

69
<ul>
710
<% post.errors.each do |error| %>
@@ -22,6 +25,7 @@
2225
</div>
2326

2427
<div>
25-
<%= form.submit %>
28+
<%= form.submit "Save Draft", name: :draft %>
29+
<%= form.submit "Publish", name: :publish %>
2630
</div>
2731
<% end %>

0 commit comments

Comments
 (0)