vendredi 25 décembre 2015

ActiveRecord::RecordNotFound in RelationshipsController#destroy

Hi i am try to build an twitter like sample app .i have created a Relationship model ,In my view i have two forms one with follow button and another one with unfollow button in my view it looks like .

<% if current_user.following?(@otheruser) %>
     <%= render 'unfollow' %>
<% else %>
     <%= render 'follow' %>
 <% end %>

and i have in _follow.html.erb like

<%= form_for(current_user.active_relationships.build) do |f| %>
  <div><%= hidden_field_tag :followed_id, @otheruser.id %></div>
  <%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>

and in _unfollow.html.erb like

<%= form_for(current_user.active_relationships.find_by(followed_id: @otheruser.id),
             html: { method: :delete }) do |f| %>
  <%= f.submit "Unfollow", class: "btn btn-danger" %>
<% end %>

in my user.rb i have methods and associations like

has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower   

  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

# Unfollows a user.

def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

whenever i am clicking follow button it is creating a entry in relationship model in relationship.rb

class Relationship < ActiveRecord::Base
    belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

but when i am clicking on unfollow button it is giving error as "Couldn't find Relationship with 'id'=" and can anyone help me to know how i can display user.followers and user.following thing.

Aucun commentaire:

Enregistrer un commentaire