我正在尝试构建一个自定义控制器操作,该操作将从与控制器相关的coffeescript文件中的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
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
答案 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_for
或form_tag
方法自动生成。在处理jQuery $.ajax({})
方法时,没有必要使用它。此外,_method
的值为patch/put/destroy
。