Rails 101 (Rails 5版) 整理post程式碼

Rails 101 (Rails 5版) 整理post程式碼

使用 before_action 修掉重複程式碼

修改 app/controllers/posts_controller.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
+ before_action :find_group, only: [:new, :create]
+ before_action :find_post, only: [:edit, :update, :destroy]

def new
- @group = Group.find(params[:group_id])
@post = Post.new
end

def create
- @group = Group.find(params[:group_id])
@post = Post.new(post_params)
@post.group = @group
@post.user = current_user

def edit
- @group = Group.find(params[:group_id])
- @post = Post.find(params[:id])
end

def update
- @group = Group.find(params[:group_id])
- @post = Post.find(params[:id])
...

def destroy
- @group = Group.find(params[:group_id])
- @post = Post.find(params[:id])
@post.destroy
redirect_to account_posts_path, alert: "Post deleted"
end

private

+ def find_group
+ @group = Group.find(params[:group_id])
+ end
+
+ def find_post
+ @group = Group.find(params[:group_id])
+ @post = Post.find(params[:id])
+ end

發文時驗證使用者是否為群組成員

修改 app/controllers/posts_controller.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
  before_action :find_group, only: [:new, :create]
before_action :find_post, only: [:edit, :update, :destroy]
+ before_action :member_required, only: [:new, :create]

private

+ def member_required
+ @group = Group.find(params[:group_id])
+ if !current_user.is_member_of?(@group)
+ redirect_to group_path(@group)
+ flash[:warning] = "你不是這個討論版的成員,不能發文!"
+ end
+ end

成果

我發表過的文章分頁功能 & 新文章排序在前

修改 app/controllers/account/posts_controller.rb

1
2
3
4
   def index
- @posts = current_user.posts
+ @posts = current_user.posts.recent.paginate(:page => params[:page], :per_page => 5)
end

修改 app/views/account/posts/index.html.erb

1
2
3
4
5
  </table>
+ <div class="text-center">
+ <%= will_paginate @posts %>
+ </div>
</div>

成果

將 post/new & edit 重複表單抽出成共用檔案

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

1
2
3
4
5
6
7
8
<%= 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 %>

app/views/posts/new.html.erb & app/views/posts/edit.html.erb 兩個檔案內重複程式碼修改為

1
<%= render "form" %>

Reference

[ 2.0 ] 6 - 0. 實做簡單的後台機制

Rails 101 (Rails 5版) 額外作業