コントローラーで取得する値をifで分岐させた話。
やりたいこと
ユーザーページ(users/show.html)で投稿記事表示の際、投稿者本人のみ公開記事を表示する。
検討
htmlでif分岐により表示を変える?
<% if current_user == @user %> 本人の内容(非公開記事を含む) <% else %> 本人以外の内容(公開記事のみ) <% end %>
htmlはそのままでcontrollerで取得するオブジェクトを調整する?
def show if current_user == @user @posts = Post.where(user_id: @user.id) else @posts = Post.where(user_id: @user.id,status_id: 2) end end
whereで指定する条件は","または".where"でOKらしい
モデル.where(条件1,条件1) モデル.where(条件1).where(条件2)
結果
controllerで取得するオブジェクトを調整でうまくいった