Rails 101 (Rails 5版) 修改發表過的文章

Rails 101 (Rails 5版) 修改已發表的文章

修改 app/controllers/posts_controller.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-  before_action :authenticate_user!, only: [:new, :create, :destroy]
+ before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]

+ def edit
+ @group = Group.find(params[:group_id])
+ @post = Post.find(params[:id])
+ end
+
+ def update
+ @post = Post.find(params[:id])
+ if @post.update(post_params)
+ redirect_to account_posts_path, notice: "Update Success"
+ else
+ render :edit
+ end
+ end

新增 app/views/posts/edit.html.erb

1
2
3
4
5
6
7
8
9
10
11
<h2 class="text-center">編輯文章</h2>
<div class="col-md-4 col-md-offset-4">
<%= simple_form_for [@group,@post] do |f| %>
<div class="form-group">
<%= f.input :content, input_html: { class: "form-control"} %>
</div>
<div class="form-actions">
<%= f.submit "Submit", disable_with: "Submiting...", class: "btn btn-primary"%>
</div>
<% end %>
</div>

成果

Rails 101 (Rails 5版) 額外作業