1
1

More than 1 year has passed since last update.

【rails】お気に入り機能一覧作成

Posted at

※※自分用メモ※※

お気に入り機能をfavoritsコントローラーで作成した為、favoritesコントローラーshowアクションで作成予定。
usersコントローラーでの作成に変更。

しかし、usersコントローラーshowアクションはもうユーザーのプロフィールページで使用中なので、
usersコントローラーfavoritesアクションを作成して、ネストを定義

①ルーティング

route.rb
  resources :users, only: [:show] do
    get :favorites, on: :member
  end

これで、/users/:id/favoritesのルーティングを設定することができる。

②コントローラー

users_controller.rb
   def favorites
      @user = User.find(params[:id])
      @favorites = current_user.favorites
    end

User.find(params[:id])でユーザーidの取得⇒@userに代入
current_user.favoritesでログイン中のユーザーのお気に入りを取得⇒@favoritesに代入

③HTML

favorites.html.erb
<% @favorites.each do |favorite| %>
    <p>投稿者:<%= favorite.user.name %></p>
    <p><%= image_tag favorite.photo.image.url if favorite.photo.image.present? %></p>
    <p><%= favorite.photo.content %></p>
    
<% end %>

②で取得した値をeach文を使い、表示させる。
<p><%= image_tag favorite.photo.image.url if favorite.photo.image.present? %></p>
if favorite.photo.image.present?でif文にすることでもし画像があればという条件分岐を行える。

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