Ajax in rails returns 总是错误回调

Ajax in rails returns alway error callback

我最近发布了同样的问题 how to use local or instance variable inruby codein coffeescript in haml templ

得到有用的评论,我试图在 ajax 中将参数传递给控制器​​,但它总是 returns 错误回调我找不到原因。

这是我的代码。

.html.haml

:coffee
$('input#field').change ->
    $.ajax
        url: '/posts/gaga'
        type: "GET"
        dataType: "json"
        data: { code: $('input#field').val() }
        error: (jqXHR, textStatus, errorThrown) ->
            alert "error"
        success: (data, textStatus, jqXHR) ->
            alert "success"

routes.rb

get 'posts/gaga'

posts_controller.rb

def gaga
    @model = Model.new
    render nothing: true
end

有人知道我的代码有什么问题吗?

提前致谢。

我认为你的路线不正确。至少应该这样格式化:

get "posts/gaga", to: "posts#gaga"

但是,如果您的 routes.rb 中已经有一个 resources :posts,这可能更符合您的需要:

resource :posts do
  collection do
    get :gaga
  end
end

因为如果您计划添加更多自定义操作,则可以避免重复 get "posts/..."