mrvncaragay
mrvncaragay

Reputation: 1260

Need to understand why: random missing required keys: [:id] error

I have a model Friendship:

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

and User Model:

 has_many :friendships
 has_many :friends, through: :friendships

User Controller:

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

Say User A added as friend User B

Then User A Added as friend User C

User B view User A

Adding and Destroying friendships works.

I'm getting an error can anyone explain why this is happening? errors goes away when User B add user C

It points out to this action:

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

No route matches {:action=>"destroy", :controller=>"friendships", :id=>nil} missing required keys: [:id]

Upvotes: 0

Views: 28

Answers (1)

Mareq
Mareq

Reputation: 1351

Just no friendship has been found. My proposal is to handle this case with something like:

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

Upvotes: 1

Related Questions