我有TrucksController
控制器有create
和location
个动作
两者都应该只被POST
个请求访问,但请求方法在控制器测试期间并不重要
无论如何,在我的控制器规格中我有
it 'redirects to the created truck' do
post :create, params: { truck: valid_attributes }
end
正如您所看到的,我清楚地告诉它转到create
操作,但它也以某种方式运行location
操作。我已将调试语句放在这两个操作中
# POST /dispatch/trucks
def create
p 'create is being called!'
p request.path
if @truck.save
redirect_to [:dispatch, @truck], notice: 'Truck added successfully'
else
alert_errors @truck
render :new
end
end
# POST /dispatch/trucks/1/location
def location
p 'location is being called!'
p request.path
location = @truck.locations.new truck_location_params
if location.save
render json: { success: true }
else
render json: { success: false }
end
end
打印两个调试代码
redirects to the created truck
"create is being called!"
"/dispatch/trucks"
"location is being called!"
"/dispatch/trucks"
这次"双重呼叫"导致其他测试失败,因为调用location
控制器操作时,truck_location_params
需要params[:location]
,此测试期间不存在location
,并且不应出现。< / p>
为什么要一次调用两个控制器动作?
如果我从控制器注释掉redirect_to
操作,所有测试仍然通过,但现在它只显示其中一个调试语句。
如果我在create
操作中注释掉location
行并取消注释location
操作,则会发现redirect_to
操作未被调用。
告诉我Rails.application.routes.draw do
# routing definitions
constraints Api do
# code
end
constraints Domain do
# code
end
# anything inside here is only accessible from a company subdomain
constraints Subdomain do
# code
namespace :dispatch do
# code
resources :trucks do
member do
get :drive
post :location # the important part
delete :drive
end
end
end
end
# code
end
导致问题。
这是我的路线
private void startWidgetAlarm(Context context){
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, ComboWidgetAlarmReceiver.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 60000, 60000, alarmIntent); //dispara cada 30 segundos desde el arranque
}
我是否误解了rails&#39;路由和重定向逻辑?
答案 0 :(得分:1)
由于某种原因,控制器动作名称表现得很奇怪。通过这样做,我能够阻止这两个动作的运行:
infer_real_valued_columns_from_input
将控制器操作从# config/routes.rb
resources :trucks do
member do
get :drive
post :location, to: 'trucks#create_location'
delete :drive
end
end
更改为location
。
由于这是一个不同的模型,最好为create_location
模型创建一个控制器,而不是让一个控制器像现在这样管理两个模型。