【问题标题】:What's the difference between respond_to and respond_with in Rails?Rails 中的 respond_to 和 respond_with 有什么区别?
【发布时间】:2015-08-25 22:31:09
【问题描述】:

当我向控制器发送数据时,出现以下错误

带参数

{"title"=>"some",
 "user_id"=>"2",
 "task"=>{"title"=>"some"}}

为什么会这样? Rails 中的 respond_to 和 respond_with 有什么区别?

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    这表示它无法识别您回复的格式。由于respond_with current_user.tasks.create(task_params) 将生成html 响应。

    在你的 routes.rb 中改变

    resources :tasks
    

    resources :tasks, :defaults => {:format => "json"}
    

    这个question 可以帮助你

    【讨论】:

    • 遗憾的是,无济于事。仍然有同样的麻烦。
    • @BillyLogan 我更新了我的答案,希望第二次尝试有效。我能够让它在我的本地机器上运行。
    • 事实证明一切都变得容易多了。我可以写respond json:
    【解决方案2】:

    试试这个:

    def create
      respond_with(current_user.tasks.create(task_params), :location => tasks_url)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2012-06-15
      • 2012-12-31
      • 1970-01-01
      相关资源
      最近更新 更多