noone__
noone__

Reputation: 69

How to delete a join table association between two models?

I have the following setup of models and controllers:

Models:

class Company < ActiveRecord::Base

  has_many :follow_companies, dependent: :destroy
  has_many :followers, through: :follow_companies, source: :user
end

#join table
class FollowCompany < ActiveRecord::Base

  attr_accessible :company_id

  belongs_to :user
  belongs_to :company
end

class User < ActiveRecord::Base

  #a user can follow many companies
  has_many :follow_companies, dependent: :destroy
  has_many :followed_companies, through: :follow_companies, source: :company
end

Controllers:

class FollowCompaniesController < ApplicationController
  def create
    company = Company.find params[:follow_company][:company_id]
    current_user.follow_companies.create! company_id:company.id
    redirect_to company
  end

  def destroy
    company = Company.find params[:id]
    current_user.follow_companies.find_by(company_id: company.id).destroy
    redirect_to company
  end
end

The join table as well as companies and users is a resource:

resources :users
resources :companies      
resources :follow_companies, only: [:create, :destroy]

Now I'd like to have buttons in my frontend for users to UNfollow a company assuming, they already follow that company: The following view is part of the Company show action and not the FollowCompany show action View:

<%= follow_company = current_user.follow_companies.find_by_company_id(@company.id) %>
<%= form_for(follow_company, :html => { :method => :delete }) do |f| %>
    <%= f.submit "Unfollow", class: "btn pull-right" %>
<% end %>

When browsing to companies/show however, I get an error in the form_for line above:

ActionController::RoutingError at /companies/10
No route matches {:action=>"destroy", :controller=>"follow_companies", :format=>nil, :id=>#<FollowCompany user_id: 2, company_id: 10, created_at: "2013-03-21 23:34:36", updated_at: "2013-03-21 23:34:36">}
Request parameters  
{"action"=>"show", "controller"=>"companies", "id"=>"10"}

Why can't rails find the route?

Upvotes: 1

Views: 420

Answers (2)

Sagar Bommidi
Sagar Bommidi

Reputation: 1409

An alternative way to achieve this without writing a form is below. If you want you can do this with a single link.

<%= link_to "Unfollow", follow_compony_path(follow_company), :method => :delete %>

Upvotes: 1

Tim
Tim

Reputation: 2891

Pretty sure you need to pull :method => :delete out of the html args:

<%= form_for(follow_company, :method => :delete) do |f| %>

Not sure if that's the only problem but that's what caught my eye.

Something like this seems a bit more elegant too (automagically creates a form):

= button_to "Unfollow", follow_company_path(follow_company), :method => 'delete'

Upvotes: 1

Related Questions