没有路由与Ajax匹配自定义控制器操作

时间:2014-11-15 21:08:29

标签: jquery ruby-on-rails ajax routes

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

然而,控制台注意到错误404并且无法访问该路线:

enter image description here

如何配置此功能以使路由和操作有效?

对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

campaigns.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

1 个答案:

答案 0 :(得分:0)

你误解了_method param。要解决问题,请更改您的ajax req:

 $.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