路由:资源,使用成员或集合进行自定义操作?

时间:2013-09-11 15:31:57

标签: ruby-on-rails ruby-on-rails-3

大家好我正在使用rails 3.2进行应用程序。我正在尝试使用form_tag,但我对路线有疑问。

我以我的形式尝试:

= form_tag('/companies/save_category', method: "post") do

和此:

= form_tag({:controller => "companies", :action=>"save_category"}, method: "post") do

在我的config/routes.rb

我对这样的路线感到有点困惑

resources :companies do
  post 'save_category'
end

或这样的路线:

resources :companies do
  member do
    post 'save_category'
  end
end

但无论哪种方式都行不通。当我执行rake routes时,我获得了相同的结果

company_save_category POST   /companies/:company_id/save_category(.:format)          companies#save_category

错误是这个

No route matches [POST] "/companies/save_category"

任何想法?

1 个答案:

答案 0 :(得分:3)

考虑以下路线:

resources :companies do
  member do
    post 'save_category'
  end
end

此成员资格块表示save_category命名空间中的路由/compagnies/需要公司ID才能生效:

/compagnies/12/save_category # where 12 is params[:company_id]

现在,收集:

resources :companies do
  collection do
    post 'save_category'
  end
end

这意味着要进入save_category路线,您不需要公司ID:

/compagnies/save_category # will work, is not needing a params[:company_id]

在您的情况下,您应该首先使用url帮助程序(在routes.rb之后生成)。你需要在这里:

if save_category is a *member route*
  save_category_company_path(@company)

elsif save_category is a *collection route*
  save_category_companies_path

我想您要保存的类别与特定公司有关,对吧?如果是,则需要成员路线:

form_tag(save_category_company_path(@company), method: "post") do

希望这有帮助!

相关问题