我想路由
[PUT] http:// foo /data/base_states/?id=8
到我的控制器,最好是这种定义:
`match '/data/base_state:id' => 'base_state#create_or_update', via: [:put]`
如何?
似乎有许多不同的方法来定义路线,文档有些缺乏。会对任何其他建议的语法(有效)感兴趣。
不知道为什么建议的路线不起作用,这是我的routes.rb和控制器......
配置/ routes.rb中
EntwineBe::Application.routes.draw do
namespace :data, defaults: {format: :json} do
resources :event_categories
resources :state_categories
resources :base_events
resources :base_states
match '/block/:bock' => 'block#show', via: [:get] # curiously, this WORKS AS EXPECTED with GET http://foo/data/block/foo
match '/base_state/:id' => 'base_states#create_or_update', via: [:put]
end
end
app / controllers / data / base_states_controller.rb
class Data::BaseStatesController < ApplicationController
before_action :set_base_state, only: [:show, :edit, :update, :destroy]
def index
@base_states = BaseState.all
end
def show
end
def new
@base_state = BaseState.new
end
def edit
end
def create # typical REST is that this is PUT
@base_state = BaseState.new(base_state_params)
respond_to do |format|
if @base_state.save
format.html { redirect_to @base_state, notice: 'Base state was successfully created.' }
format.json { render action: 'show', status: :created, location: data_base_state_url(@base_state) }
else
format.html { render action: 'new' }
format.json { render json: @base_state.errors, status: :unprocessable_entity }
end
end
end
def create_or_update
logger.info "WTF"
end
def destroy
@base_state.destroy
respond_to do |format|
format.html { redirect_to base_states_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_base_state
@base_state = BaseState.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def base_state_params
params.require(:base_state).permit(:foo, :bar)
end
end
'佣金路线'的相关输出
data GET /data/block/:block(.:format) data/code_block#show {:format=>:json}
PUT /data/base_state/:id(.:format) data/base_states#create_or_update {:format=>:json}
PUT /data/base_state:id(.:format) base_state#create_or_update {:format=>:json}
示例调用
$.ajax({'type':'PUT', 'url':'/data/base_state?id=8'})
$.ajax({'type':'PUT', 'url':'/data/base_state/?id=8'})
$.ajax({'type':'PUT', 'url':'/data/base_state?id=8.json'}) // not that expect it to need / I want to have .json
$.ajax({'type':'PUT', 'url':'/data/base_state/?id=8.json'}) // not that expect it to need / I want to have .json
- &GT;的 404 <!/强>
答案 0 :(得分:0)
将defaults: {format: :json}
添加到您的路线中。
match '/data/base_state:id' => 'base_state#create_or_update', via: [:put], defaults: {format: :json}
答案 1 :(得分:0)
put '/data/base_state:id' => 'base_state#create_or_update', defaults: { format: :json }
答案 2 :(得分:0)
put "data/base_state:id(.:format)" => 'base_state#create_or_update'
答案 3 :(得分:0)
希望我对此并不太晚!
如果您的路线为/data/base_state/:id
,那么您用来查看ID为8的匹配资源的网址为/data/base_state/8.json
。
正如spas正确指出的那样,如果你在ajax调用dataType: 'json'
中设置了正确的数据类型,那么你不需要在URL的末尾添加.json