Jean Jean - 5 months ago 13
Ruby Question

How to send location after `create` action

I have the following

create
action:

def create
episode = Episode.new(episode_params)
if episode.save
render json: episode, status: :created, location: episode
end
end


but when I test the following:

require 'test_helper'

class CreatingEpisodesTest < ActionDispatch::IntegrationTest
setup { host! 'api.example.com'}

test 'create episodes' do
post '/episodes',
{ episode:
{ title: 'Bananas', description: 'Learn about bananas.' }
}.to_json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s }

assert_equal 200, response.status
assert_equal Mime::JSON, response.content_type

episode = json(response.body)
assert_equal "/episodes/#{episode[:id]}", response.location
end
end


I get the following error:

1) Error: CreatingEpisodesTest#test_create_episodes: NoMethodError: undefined method `episode_url' for #<API::EpisodesController:0x007f8e34519450> Did you mean? episode_params
app/controllers/api/episodes_controller.rb:11:in `create'
test/integration/creating_episodes_test.rb:7:in `block in #<class:CreatingEpisodesTest>'

1 runs, 0 assertions, 0 failures, 1 errors, 0 skips


I guest I miss something to send the location after I create the episode.

UPDATE: Route



Rails.application.routes.draw do
namespace :api, path: '/', constraints: { subdomain: 'api' } do
resources :zombies
resources :episodes
end
end

Answer

This is because of namespace, use [:api, episode] for location