問題描述
ruby on rails 友誼以下節目總是我的名字 (ruby on rails friendship following shows always my name)
friendship.rb
belongs_to :user, :include => [:profile]
belongs_to :friend, :class_name => 'user'
user.rb
#following code
has_many :friendships
has_many :friends, :through => :friendships
#followers code
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
using this code to display who i have friended and who has friended me
view
<h2>Friends</h2>
<ul>
<% for friendship in @user.friendships.includes(:user) %>
<li>
<%= friendship.user.username %>
(<%= link_to "remove", friendship, :method => :delete %>)
</li>
<% end %>
</ul>
<p><%= link_to "Find Friends", users_path %></p>
<h2>Friended by Users</h2>
<ul>
<% for user in @user.inverse_friends %>
<li><%=h user.username %></li>
<% end %>
</ul>
on the first loop block i always get my username printed, lets call it "fxuser" on the second loop block i get the correct usernames of who have friended me...
how can this be solved so the first loop will display the correct usernames of who i have friended?
參考解法
方法 1:
In your first loop I believe friendship.user
is referring back to yourself; you're looking for the friendship.friend
. Also, I think you want to be removing the friendship
, not the inverse in the delete link.
<% for friendship in @user.friendships.includes(:friend) %>
<li>
<%= friendship.friend.username %>
(<%= link_to "remove", friendship, :method => :delete %>)
</li>
<% end %>
You also need to change
belongs_to :friend, :class_name => 'user'
to
belongs_to :friend, :class_name => 'User'