Rails 中的respond_to 和respond_with 有什么区别? [英] What's the difference between respond_to and respond_with in Rails?
本文介绍了Rails 中的respond_to 和respond_with 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我向控制器发送数据时出现以下错误
When I'm sending data to my controller I'm getting the following error
带参数
{"title"=>"some",
"user_id"=>"2",
"task"=>{"title"=>"some"}}
为什么会这样?Rails 中的respond_to 和respond_with 有什么区别?
Why is that so? And what's the difference between respond_to and respond_with in Rails?
class TasksController < ApplicationController
respond_to :json
def create
respond_with current_user.tasks.create(task_params)
end
private
def task_params
params.require(:task).permit(:id, :title, :due_date, :priority, :complete)
end
end
当我使用 respond_to 时,它说 Undefined method upcase for Task
When I'm using respond_to it says Undefined method upcase for Task
推荐答案
它表示它无法识别您的响应格式.由于 respond_with current_user.tasks.create(task_params)
将生成 html
响应.
It's saying it doesn't recognize the format of your response. Since respond_with current_user.tasks.create(task_params)
will generate a html
response.
在你的 routes.rb 更改
In your routes.rb change
resources :tasks
到
resources :tasks, :defaults => {:format => "json"}
这个问题可能对你有帮助
这篇关于Rails 中的respond_to 和respond_with 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文