LoginSignup
1
1

More than 3 years have passed since last update.

scope使い方(Rails)

Posted at

modelの中にscopeを書く

複数使う場合はスコープで書いた方がコードが読みやすくなりますし、
単体テスト書くことが可能になるため積極的に使った方がいいです。

item.rb
 scope :published, -> { where(private: true) }
users_controller.rb
 def show
    if !@user.me?(current_user)
      @items = @user.items.published
    else
      @items = @user.items
    end
  end

モデルで{ where(private: true) }定義することで
コントローラの記述が少なくなります。

おまけ

user.rb
def me?(user_id)
  id == user_id
end

current_user@userが一致しているか
モデルに書くことで可能になります。

users_controll.rb
if !@user.me?(current_user)
1
1
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
1
1