Rails 3为资源添加新路由

时间:2013-05-25 12:19:25

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

我有以下问题:

我使用命令“scaffold”创建了一个实体“Film”并自动添加到我的路径文件“resources:films”中,然后我尝试通过ajax添加自动完成,但总是调用ajax调用“show”行动而不是调用我添加“autocomplete_term”的路线

我的路线档案(routes.rb)

resources :films

我尝试了以下可能性(routes.rb)

match 'films/autocomplete_term' => "films#index", :via=>:get
match "films/autocomplete_term/:term" => "films#autocomplete_term",    :controller=>"films", :action=>"autocomplete_term", :as => :films_autocomplete, :via => :get
resources :films do
  collection do
    get 'autocomplete_term'
  end
end

路线

** localhost.com:3000/films/autocomplete_term?term=a **

错误

无法找到id = autocomplete_term

的电影

app / controllers / films_controller.rb:28:在'show'

当我运行命令rake routes

  GET    /films/autocomplete_term/:term(.:format) films#autocomplete_term
  films_autocomplete 
  GET    /films/autocomplete_term/:term(.:format) films#autocomplete_term

autocomplete_term_films       GET /films/autocomplete_term(.:format)电影#autocomplete_term

抱歉我的英文

并提前致谢

2 个答案:

答案 0 :(得分:0)

访问此路线的网址

GET    /films/autocomplete_term/:term

应该是

localhost.com:3000/films/autocomplete_term/a

如果你localhost.com:3000/films/autocomplete_term?term=a它会认为这是show动作,它会忽略?term = a

GET    /films/:id

答案 1 :(得分:0)

感谢Anezio解决了这个问题,困境有两件事:

1 - 路线

match "films / autocomplete_term /: term"

2:routes.rb文件中的顺序(Rails路由按照指定的顺序匹配)

resources: films
match 'films / autocomplete_term /: term' => "films # autocomplete_term"

最终解决方案:(routes.rb)

match 'films / autocomplete_term' => "films # autocomplete_term"
resources: films