LoginSignup
0
0

More than 5 years have passed since last update.

コントローラーをなるべく活用してビューを綺麗にする(随時更新)

Posted at

なるべくビューから情報を消したかった。

一度作ったwebサービスがあるのですが、あまりにも汚かったので、初心者なりにリファクタリング中です。
やっていて感じたことが、コントローラーで取れる情報は、コントローラーで取り、ビューから取れるものはビューから取るというものです。

current_user.idはコントローラーで取れる

初心者なんで許していただきたいですが、今まで自分はいちいちcurrent_user.idをviewから取得していましたが、よくよく考えたらコントローラーでも取れますよね。

example.html.erb
<%= link_to "POST", new_post_path(post_id: id, user_id: current_user.id), :method => 'post' %>

みたいな感じで書いていたのですが、user_id: current_user.idがいらなかったなあと。

example.html.erb
<%= link_to "POST", new_post_path(@post) %>
posts_controller.rb
post = Post.find(params[:id])
Post.create(id: post.id, user_id: current_user.id)

といった感じでできてしまいますね。。

selfはレシーバのidを取れる

レシーバであるインスタンスの情報をコピーできるselfですが、これも最初の頃は全く使っていませんでした。
本当はこのselfすら省略できるそうですが、自分の勉強のために明示的に書いています。

例えばいいね機能を作るときなどに。。。。

bookテーブルとuserテーブルがあり、中間テーブルとしてbook_userテーブルがあるとしたら。。。。

def like
 bookuser =  BookUser.find(params[:id])
 bookuser.create(user_id: current_user.id, book_id: self.id)
end

などで使えます。

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