开发者

Rails 3 - Truncate in a Controller?

开发者 https://www.devze.com 2023-01-21 08:49 出处:网络
I开发者_运维问答n my controller, I\'m building a json object for books. I want to show truncate(book.content, 250).

I开发者_运维问答n my controller, I'm building a json object for books. I want to show truncate(book.content, 250).

This 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.


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.


You can just call the truncate rails string method.

http://apidock.com/rails/String/truncate

"Once upon a time in a world far far away".truncate(27)

@book.content.truncate(250)

Not 100% sure if you have to include

include ActionView::Helpers::TextHelper
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号