3

I was using a html and json response with the classic respond_to do |format| but now I was trying to implement a xhr data load and, after a while searching, this was my solution (with the corresponding js and html templates):

respond_to :html, :js, :json
# GET /messages
def index
  @search = Messages.valid.search(params[:search])
  @messages = @search.paginate(:page => params[:page])
  respond_with(@messages, :layout => !request.xhr?)
end

The html and js responses works correctly, but now if I want to call something like /messages.json it throws me:

ArgumentError in MessagesController#index

There was no default layout for MessagesController in [#<ActionView::FileSystemResolver:0x1064c23c0 @caching=false, @path="/Users/alter/workspace/trilog/app/views", @cached={}>]

How respond_with handle these kind of data types? And what should I do to make responses in all the different format types?

Thanks in advance

Update

As appears here I've added a index.json.haml template with only one line =@messages.to_json.html_safe but I don't think that add a template for json type would the best solution. Any idea?

Community
  • 1
  • 1
Alter Lagos
  • 12,090
  • 1
  • 70
  • 92

1 Answers1

0

For JSON, I just use:

respond_to do |f|
    f.json { render json: @messages }
end

That doesn't really fit in with using respond_with, perhaps; what makes the most sense might depend on how many actions, controllers, etc. would need to be modified.

I'll be interested to see what other answers entail.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302