【问题标题】:No Route Matches Custom Controller Action with Ajax没有路由匹配带有 Ajax 的自定义控制器操作
【发布时间】:2014-11-15 21:08:28
【问题描述】:

我正在尝试构建一个自定义控制器操作,该操作将从与控制器相关的咖啡脚本文件中的 ajax 接收参数。

但是控制台提示错误 404 并且无法访问该路由:

如何配置它以使路由和操作正常工作?

对campaigns_controller 的控制器操作:

def create_campaign_location_relationship
    @location = Location.find(params[:location_id])
    @campaign = Campaign.find(params[:id])

    @insert = CampaignLocation.new(campaign_id: @campaign.id,
                                   location_id: @location.id)
    @insert.save
end

campaign.js 中的 ajax

  $('[name=commit]').bind "click", ->
    # Insert the code to allow for a user to 
    alert "Relationships created"

    selectedLocations = root.table.rows(".selected").data()
    for locationSelected in selectedLocations
      location_id = locationSelected[0]
      $.ajax({
        url: "create_campaign_location_relationship/" + location_id,  
        type: "post",
        dataType: "json"
      })

    return

活动路线:

  resources :campaigns,   only: [:create, :edit, :update, :destroy, :show]

  resources :campaigns do 
    member do 
      match "/create_campaign_location_relationship/:location_id", to: "campaigns#create_campaign_location_relationship", via: 'post' 
    end 
  end

【问题讨论】:

    标签: jquery ruby-on-rails ajax routes


    【解决方案1】:

    您误解了_method 参数。要解决您的问题,请更改您的 ajax 请求:

     $.ajax({
        url: "/create_campaign_location_relationship" + location_id,  
        type: "post",
        dataType: "json"
      })
    

    这里不需要使用_method。另请注意,您已将create_campaign_location_relationship 定义为get,而它必须是post

    _method 是一个隐藏字段,通常在表单标签中使用,由form_forform_tag 方法自动生成。在处理 jQuery $.ajax({}) 方法时,没有必要使用它。此外,_method 采用值 patch/put/destroy

    【讨论】:

    • 在我将get 更改为post 和ajax 更改的路由中,我仍然在控制台中收到错误404
    • 我的意思是服务器日志,比如Started POST ... 等等。
    • 这很有趣。看看campaigns/campaigns/...(双campaigns)。既然如此,请从 url 中删除 campaigns,使其变为:“/create_campaign_location_relationship”+ location_id`(带有前面的/)。
    • 我想通了。我将路由更改为:match "/create_campaign_location_relationship/:location_id", to: "campaigns#create_campaign_location_relationship", via: 'get',因此使用get 代替post 允许它工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 2016-04-29
    • 2016-01-14
    • 2023-03-31
    • 2016-04-05
    相关资源
    最近更新 更多