我有以下模型和控制器设置:
型号:
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
控制器:
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
联接表以及公司和用户是一种资源:
resources :users
resources :companies
resources :follow_companies, only: [:create, :destroy]
现在我想在我的前端设置按钮让用户关注公司假设,他们已经关注该公司: 以下视图是Company show action的一部分,而不是FollowCompany show action 视图:
<%= 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 %>
当浏览公司/ show时,我在上面的form_for行中收到错误:
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"}
为什么无法找到路线?
答案 0 :(得分:1)
很确定你需要拉:method =&gt; :删除html args:
<%= form_for(follow_company, :method => :delete) do |f| %>
不确定这是否是唯一的问题,但这是引起我注意的问题。
这样的东西似乎也更优雅(自动创建表单):
= button_to "Unfollow", follow_company_path(follow_company), :method => 'delete'
答案 1 :(得分:1)
下面是在不编写表单的情况下实现此目的的另一种方法。如果您愿意,可以通过一个链接完成此操作。
<%= link_to "Unfollow", follow_compony_path(follow_company), :method => :delete %>