views:

35

answers:

1

Hello, in my controller I'm building a json object for books. I want to show truncate(book.content, 250)

but that doesn't work in a rails controller? And given it's a JSON render, I don't use a view. So how does one truncate? I don't want my JSON object to be huge :)!

thanks

+2  A: 

You can use many ways to accomplish this. The most conviniet one would be to just include the proper helper in the controller. In this it would be:

class BooksController < ApplicationController
  include ActionView::Helpers::TextHelper
  ...
end

Alternatively you can also create a partial which generates the code you need, for example _truncate.html.erb with proper code:

<%= truncate (@book, :length => 250) %>

And then render it in your view:

result = render_to_string :partial => 'truncate'

Hope this helps.

mdrozdziel
Thanks, I was doing truncate(@book, 200) and that was erroring... When I used the :length it worked? Strange.. YOu don't need length in views..
TheExit
truncate(@book, 200) syntax is deprecated for some time now, and the proper way to use truncate is to pass options hash after the object. I am not sure, why deprecated method worked in views and not in controller, but you should just stick to the new syntax. :-)
mdrozdziel