こんにちは。ruby on railsに関する質問となります。
中間テーブルとして以下のFriendshipを作りました。
lang
1class Friendship < ActiveRecord::Base 2 belongs_to :user, 3 class_name: :User, 4 foreign_key: :user_id, 5 primary_key: :twitter_id 6 7 belongs_to :friend, 8 class_name: :User, 9 foreign_key: :friend_id, 10 primary_key: :twitter_id 11end
これは以下のUserモデルのtwitter_id同士による関連付けをするためのものです
lang
1User 2-id 3-twitter_id
ここで、current_user(User)のfriendsへ指定のtwitter_idを持つユーザーを追加するには以下で実現できました
lang
1current_user.friends << User.find_by(twitter_id: params[:friend_id])
しかし、これはUserにtwitter_idを持つデータがなければ実現しません。
Friendshipでは、オーナーのidとターゲットのidだけが必要なため、以下のように直接Friendshipを生成しましたが、
lang
1Friendship.create(:user_id => current_user.twitter_id, :friend_id => friend_id)
lang
1user.friends
で上記の直接生成したFriendshipを表示することが出来ませんでした。
試した所、上記の直接生成する方法ではターゲットのidが存在してもuser.friendsには含まれませんでした。
上手く説明出来ているか分からないのですが是非解説頂けると幸いです。
##追記
Userモデル
lang
1class User < ActiveRecord::Base 2 has_many :friendships, 3 dependent: :destroy 4 has_many :friends, 5 through: :friendships 6end 7
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/04/21 22:53
2015/04/21 23:07
2015/04/22 00:40