简体   繁体   中英

What's the difference between respond_to and respond_with in Rails?

When I'm sending data to my controller I'm getting the following error

在此处输入图片说明

with the parameters

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

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

When I'm using respond_to it says Undefined method upcase for Task

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.

In your routes.rb change

resources :tasks

to

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

This question may help you

Try this one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM