前提・実現したいこと
勉強の為RubyOnRailsでブログサイトを作っています。
Modleの構造とViewでの表示で悩んでいます。
現在のModleの構造と致しましては
・Userモデル(UserProfileモデルと1:1で紐付けています。deviseを使い登録機能を実装しています。)
・UserProfileモデル(Postモデルと1:nで紐付いています。登録したユーザのプロフィールを扱っています。)
・Postモデル(登録したユーザの投稿機能です。)
現状はこの様に
・Userモデルに対してUserProfileモデルを1:1, UserProfileモデルにPostモデルを1:nの関係性にしています。
そして、エンドユーザに表示する為にShowUsersControllerを作りそこのindexに各紐ついたユーザ情報を表示していきたいです。
発生している問題・エラーメッセージ
・Modelの構造として
今回の場合ただ段階的にUser→UserProfile→Postと紐付けるのではなく
UserモデルにUserProfileモデルを1:1そして更にUserモデルにPostモデルを1:nした方が
作っていく上で綺麗な形になるのでしょうか?
・Viewでの表示について
ShowUsersControllerのindexで各紐付いているユーザ情報を表示する際
ShowUserController側でどの様な処理を書けばよろしいでしょうか?
Showの詳細部分などは画面遷移された際にパラメータからidを受け取ってそこから紐付いているモデルを表示させる処理はわかるのですがindexの方に関して変に詰まってしまいます。
includesを使ってmodel同士をまとめて取得しViewの方でeachで回して表示していけばよろしいのでしょうか?
とても長文になってしまい申し訳御座いません。
読んでいただきありがとう御座います。
ご教授頂けたらと幸いです。
何卒よろしくお願い致します。
該当のソースコード
Ruby
1class ShowusersController < ApplicationController 2 3 def index 4 @user = current_user 5 6 end 7 8 def show 9 # パラメータからcurrent_userのidを取得,処理を書く 10 11 # 取り出したユーザidと紐付いているUserProfileを取り出して 12 @user_profile = UserProfile.where(user_id: @user.id) 13 # 更に取り出したUserProfileに紐付いているPostを取り出す 14 @post = Post.where(user_profile_id: @user_profile.ids) 15 end 16end
Ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 # user_profleモデルと1:1の紐付け 8 has_one :user_profile, dependent: :destroy 9end 10
Ruby
1class UserProfile < ApplicationRecord 2 # userモデルと1:1の紐付け 3 belongs_to :user 4 # postモデルと1:nの紐付け 5 has_many :posts, dependent: :destroy 6 # carrierwave 7 mount_uploader :image, ImageUploader 8end 9
Ruby
1class Post < ApplicationRecord 2 # userprofileと1:nの紐付け 3 belongs_to :user_profile 4end 5
Ruby
1showusers/index 2<h1>エンドユーザトップページ</h1> 3<%= @user.name %> 4<% @post.each do |post| %> 5<div class="card card-body bg-light"> 6 <div class="title"> 7 <%= link_to user_profile_path(post.id) do %> 8 <%= post.title %> 9 <% end %> 10 </div> 11 <div class="active_area"> 12 活動地域: <%= post.user_profile.active_area %> 13 </div> 14 <div class="language"> 15 言語: 16 </div> 17 <div class="experience"> 18 経験年数: 19 </div> 20 <div class="text"> 21 <%= post.text %> 22 </div> 23</div> 24<% end %> 25<p>--------------<br></p>
回答1件
あなたの回答
tips
プレビュー