RileyE
RileyE

Reputation: 11074

Undefined method with `respond_with`

EDIT: I would like to know why Ruby/Rails is deciding to look for a function called word_list_url in my controller. Normally everything makes sense as to why it's done in RoR, but this doesn't make sense to me.

I'm trying to respond_with a model object in one of my controller functions like so:

def create
   @word_list = WordList.new(params[:word_list])
   @word_list.key = randomKey
   if @word_list.title == nil then @word_list.title = "No Title"
   end
   if @word_list.words == nil then @word_list.words = "Empty"
   end
   @word_list.save
   respond_with @word_list
end

Then I'm calling the API like so:

curl -v -H "Content-Type: application/json" -X POST -d '{"title":"New Word List", "words":"Words\nFor\nThe\nWord\nList"}' http://localhost:3000/create.json

But I'm getting the error:

NoMethodError (undefined method `word_list_url' for #<WordListsController:0x007fb34c95ca98>):
  app/controllers/word_lists_controller.rb:42:in `create'

However, this is the model:

class WordList < ActiveRecord::Base
  attr_accessible :key, :title, :words
end

Where is it getting the "method word_list_url" from? I'm not fully sure what is going on. I have my respond_to:

respond_to :json, :xml

What is going on here? If I use render instead of respond_with, everything works just fine.


Currently, in other functions, respond_with is working just fine. For example:

  def show
    lists = WordList.where(:key => params[:id].upcase)
    if lists.length > 0 then @word_list = lists.first
    elsif numberValue(params[:id]).between?(0, WordList.count) then @word_list = WordList.find(params[:id])
    end
    respond_with(@word_list)
  end

Routes:

create POST   /create(.:format) word_lists#create
update PUT    /update(.:format) word_lists#update
       GET    /:id(.:format)    word_lists#show

Upvotes: 1

Views: 2056

Answers (1)

jvnill
jvnill

Reputation: 29599

if you look at http://api.rubyonrails.org/classes/ActionController/Responder.html, you'll see that having support for xml format expands to

format.xml { render :xml => @word_list, :status => :created, :location => @word_list }

I think :location uses url_for which may cause your error. try

respond_with @word_list do |format|
  format.xml { render :xml => @word_list, :status => :created }
end

Upvotes: 1

Related Questions