需要了解原因:随机缺少必需的键:[:id]错误

时间:2016-01-14 20:21:25

标签: ruby-on-rails ruby-on-rails-4

我有一个模特友谊:

 belongs_to :user
 belongs_to :friend, class_name: 'User'

和用户模型:

 has_many :friendships
 has_many :friends, through: :friendships

用户控制器:

 @user = User.find_by!(username: params[:username])
 @user_following = @user.friends.all
 @user_followers = @user.inverse_friends.all

假设用户A添加为朋友用户B

然后用户A添加为朋友用户C

用户B查看用户A

Adding and Destroying friendships works.

我得到一个错误,任何人都可以解释为什么会这样吗? 用户B添加用户C

时,错误消失

它指出了这一行动:

<%= button_to "following", friendship_path(current_user.friendships.find_by(friend_id:following.id)), method: :delete %>
  

没有路线匹配{:action =&gt;“destroy”,:controller =&gt;“friendships”,   :id =&gt; nil}缺少必需的键:[:id]

1 个答案:

答案 0 :(得分:1)

没有找到任何友谊。我的建议是通过以下方式处理此案例:

<% if friendship = current_user.friendships.find_by(friend_id: following.id) %>
  <%= button_to "following", friendship_path(friendship), method: :delete %>
<% else %>
  <%= "No friendship found" %>
<% end %>