0
0

More than 3 years have passed since last update.

Model名とController名が異なっていてもデータ移動はできるらしい 学習37日目

Posted at

〇〇モデルのデータは□□コントローラー上でも使える

UserモデルのデータはUsersコントローラーで,Pageモデルのデータはpagesコントローラーでという大きな思い込みをしていた。(冷静に考えれば、application.html.erbはいろんなモデルからデータを取ってきている)

勘違いしていたこと

1.モデルとコントローラーのデータのやり取りは、同じ名前同士で行う。←そんなことない!

UserモデルのデータはUsersコントローラーで,Pageモデルのデータはpagesコントローラーでという大きな思い込みをしていた。(冷静に考えれば、application.html.erbはいろんなモデルからデータを取ってきている)

2.controllerの内容を継承したければコピペする←それだけではない!

確かにuserscontrollerの内容をそのままpagescontrollerでも使いたければ、コピペも1つの手段になる。しかしめんどくさいのでclassを継承をすれば良い(pagescontroller<userscontroller)

下記の例はpagesと名付けたshowのviewである。ここには@userを用いている。そしてその下はpagesコントローラーである。

show.html.erb(pages)
<div class="container">
<div class="profile-card">
  <div class="profile-card__inner">
  <div class="profile-thumb">
    <img src="<%="/user_images/#{@user.image_name}" %>" class="user-image" alt="アイコン">  

    </div>
    <div class="profile-content">
    <span class="profile-name"><%=@user.name%></span>
    <span class="profile-job"><%=@user.email %></span>
    <span class="profile-intro"><%=@user.intro %></span>
    <%=link_to("編集する",edit_user_registration_path, method: :get) %>
    </div>
    </div>

</div>
</div>
class PagesController < UsersController
def index
    @users = User.all
end

def show 
    @user = User.find_by(id: params[:id])
end


def update 
    @user = User.find_by(id: params[:id])
    @user.name = params[:name]
    @user.intro = params[:intro]

    if params[:image]
        @user.image_name = "#{@user.id}.jpg"
        image = params[:image]
        File.binwrite("public/user_images/#{@user.image_name}", image.read)
      end

      if @user.save
        flash[:notice] = "ユーザー情報を編集しました"
        redirect_to("/pages/#{@user.id}")
      else
        render("users/edit")
      end


end

def edit
    @user = User.find_by(id: params[:id])
  end

end

↑↑Pagescontroller<Userscontrollerしてるからコピペしなくていい(しちゃってる悪い例)
@user = User.allは別にpagescontrollerでも使える

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