LoginSignup
0
0

More than 3 years have passed since last update.

RailsでExtend(Concerns)を利用してControllerの処理を共通化する。

Last updated at Posted at 2021-01-10

背景

記事一覧をPage#homeに出力したかった。
@ posts = Post.allのデータは、Postモデル、コントローラにある。Pageモデル、コントローラには無い。
PostのデータをPageに持ってくるためにはどうすればいいかググっていた。

解決

この情報をPageに持って行きたい。

posts_controller.rb
class PostsController < ApplicationController

    def index
      posts = Post.all
    end
end

Pageに取り込む。

Page.rb
class Page < ApplicationRecord

   + extend Post::Models

end

PageでPostの情報を定義してみる。

pages_controller.rb
def home
  @posts = Post.all
end

出力された。

home.html.erb
<%= @posts.each do |p| %>
 <%= p.thumbnail %>
 <%= p.title %> 
 <%= p.tag %> 
 <%= p.content %> 
<% end %> 

もっとうまく説明している記事あります。↓
https://github.com/mc-chinju/qiita_clone/commit/262a6178d5a2eb77c6f507cf9386cb61825bfbaf
https://medium.com/@yavuz255/rake-aborted-2da1233a4561
https://railsguides.jp/active_model_basics.html

他のやり方↓
controller/concernにファイルを作って行う方法
https://programming-beginner-zeroichi.jp/articles/142

ググる時の関連ワード

extend ActiveSupport::Concern
rails concern

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0