【发布时间】:2012-01-31 12:35:30
【问题描述】:
我阅读了开始发布此问题时弹出的所有答案,但它们似乎无法解决我的问题。
我向我的控制器添加了一个名为 get_results 的新操作(除了通过脚手架创建的操作),但每次我更改选择菜单中的选项时,它都会指示我“编辑”操作,而不是“get_results” ",
这是js
<script type="text/JavaScript">
$(function(){
$('.menu_class').bind('change', function(){
$.ajax('#{:controller => "my_tests", :action => "get_results"}?param_one=' + $(this).val());
});
});
</script>
编辑:这是对我有用的 js 代码,感谢 Robin 在下面的回答:
<script type="text/JavaScript">
$(function(){
$('.menu_class').bind('change', function(){
$.ajax({
url: "<%= get_results_my_tests_url %>",
data: {
param_one: $(this).val()
}
});
});
});
</script>
这是我添加的动作(sn-ps)
def get_results
# some stuff goes here
respond_to do |format|
if @my_test.update_attributes(params[:my_test])
format.html
format.js
else
format.html { render :action => "update" }
format.json { render :json => @my_test.errors, :status => :unprocessable_entity }
end
end
end
我在我的 routes.rb 中为它添加了一条特定的路线
MyTests::Application.routes.draw do
resources :my_tests
get "home/index"
match '/my_tests/get_results' => 'my_tests#get_results', :as => :get_results
match ':controller(/:action(/:id(.:format)))'
root :to => 'home#index'
end
编辑:这是对我有用的路线配置,感谢 Robin 在下面的回答:
resources :my_tests do
collection do
get :get_results
end
end
rake routes 给了我这个
my_tests GET /my_tests(.:format) {:action=>"index", :controller=>"my_tests"}
POST /my_tests(.:format) {:action=>"create", :controller=>"my_tests"}
new_my_test GET /my_tests/new(.:format) {:action=>"new", :controller=>"my_tests"}
edit_my_test GET /my_tests/:id/edit(.:format) {:action=>"edit", :controller=>"my_tests"}
my_test GET /my_tests/:id(.:format) {:action=>"show", :controller=>"my_tests"}
PUT /my_tests/:id(.:format) {:action=>"update", :controller=>"my_tests"}
DELETE /my_tests/:id(.:format) {:action=>"destroy", :controller=>"my_tests"}
home_index GET /home/index(.:format) {:action=>"index", :controller=>"home"}
get_results /my_tests/get_results(.:format) {:action=>"get_results", :controller=>"my_tests"}
/:controller(/:action(/:id(.:format)))
root / {:action=>"index", :controller=>"home"}
那么为什么它总是指示我“编辑”操作而不是“get_results”?
【问题讨论】:
-
没有任何错误?我希望它尝试使用“get_results”作为 ID,因为您的匹配是在“资源”路由之后。您没有添加 RESTful 操作的任何原因?另外,请用适当的 Rails 版本标签标记问题。
-
不。如果我将浏览器指向 my_tests/get_results,则会收到此错误“找不到带有 id=get_results 的 MyTest” 这是我在服务器上看到的跟踪 Started GET "/my_tests/11/edit" for 127.0.0.1 at Sun Jan 01 15:20:54 -0800 2012 由 MyTestsController#edit 处理为 / 参数:{"id"=>"11"} MyTest Load (0.4ms) SELECT "my_tests".* FROM “我的测试”在哪里“我的测试”。“id”=? LIMIT 1 [["id", "11"]] 渲染 my_tests/_form.html.erb (9824.6ms) 在布局/应用程序中渲染 my_tests/edit.html.erb (9828.1ms) 在 9847ms 内完成 200 OK (查看次数: 9843.4 ms | ActiveRecord: 0.9ms)
-
查看earlier answer of mine,这是同样的问题。遇到错误时,应将其包含在问题中。
-
@Dave:感谢您的指点。我将其更改为资源 :my_tests do get 'get_results', :on => :collection end 并评论了匹配线,但仍然没有运气;-(
-
用当前代码更新问题。你修复了 JS 吗?
标签: javascript jquery ruby-on-rails routes