練習がてらRailsでTwitterもどきを作っています。
UsersテーブルとFollowsテーブルの2つのテーブルがあり、カラム構成はそれぞれ下記の通りです。
Usersテーブル
id
, user_name
, email
, password
Followsテーブル
id
, following_user_id
, followed_user_id
Viewで、自分がフォローしているユーザーと、自分をフォローしているユーザー(フォロワー)のuser_name
の一覧をそれぞれ表示したいのですが、どうしたらいいでしょうか。
現状のコードです↓
user.rb
has_many :follows, dependent: :destroy
follow.rb
belongs_to :user, foreign_key: 'followed_user_id'
follows_controller.rb
def index @followings = Follow.all.where(following_user_id: current_user.id) @followers = Follow.all.where(followed_user_id: current_user.id) end
index.html.erb
<h2>Followings</h2> <% @followings.each do |following| %> <p><%= following.user.user_name %></p> <% end %> <h2>Followers</h2> <% @followers.each do |follower| %> <p><%= follower.user.user_name %></p> <% end %>
これだと自分がフォローしているユーザーのuser_name
はきちんと取得できるのですが、フォロワーのuser_name
が取得できずに困っています。
follow.rb
のforeign_key
をfollowing_user_id
にすればフォロワーのuser_name
を取得できますが、そうすると今度はフォローしているユーザーの方が取得できなくなってしまいます。ひとつのモデルでこの2つが両方動くようにするにはどのように記述したら良いのでしょうか?(foreign_keyを2つ持たせるなんてできないし...。)どなたかご教示いただけますと幸いです。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/27 06:13