Rails 101 (Rails 5版) 整理post程式碼
使用 before_action 修掉重複程式碼
修改 app/controllers/posts_controller.rb
1 | before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy] |
發文時驗證使用者是否為群組成員
修改 app/controllers/posts_controller.rb
1 | before_action :find_group, only: [:new, :create] |
成果
我發表過的文章分頁功能 & 新文章排序在前
修改 app/controllers/account/posts_controller.rb
1 | def index |
修改 app/views/account/posts/index.html.erb
1 | </table> |
成果
將 post/new & edit 重複表單抽出成共用檔案
新增 app/views/posts/_form.html.erb
1 | <%= simple_form_for [@group,@post] do |f| %> |
將 app/views/posts/new.html.erb
& app/views/posts/edit.html.erb
兩個檔案內重複程式碼修改為
1 | <%= render "form" %> |