Reputation: 389
I have an app that creates text excerpts from body text entered into the model and it seems to work fine except, for some reason, when i try to enter one particular string into the body text.
in my blog_post model I have
t.string "excerpt", limit: 114
in my controller i am creating the excerpt string by doing this:
def create
@blogpost = Blogpost.new(blogpost_params)
@excerpt = @blogpost.body
@blogpost.excerpt = truncate(@excerpt, :length => 114)
respond_to do |format|
if @blogpost.save
etc,etc,
end
This seems to work fine most of the time but i entered the following text as a test
You know how they used to say It's #Sinatra's world, the rest of us are just living in it. - well, it's as true today as it was then. Check out Frank. When he gets out of a #chopper, dressed in a perfect lounge suit, #cocktail in hand, his #hat stays perfectly tilted. When I get out of a #chopper (and I'm not talking about once or twice but every single time I ever get out of a chopper) the spinning blades blow my hat all over the place. #Milliners should think about that and you should too the next time you're out hat shopping.
(sorry it's a bit long) I get the following error:
ActiveRecord::StatementInvalid in MoansController#create
Mysql2::Error: Data too long for column 'excerpt' at row 1....
It looks like the truncate isn't working for some reason.. Is it something to do with this text or have i missed something else?
Upvotes: 1
Views: 1797
Reputation: 8954
I think you should remove the database restriction and handle this by using a setter that truncates to the wanted length by default. In you model add excerpt_setter
to the attr_accessible
list. And then define it like this
def excerpt_setter=(str)
self.excerpt = truncate(str, :length => 114)
end
def excerpt_setter
self.excerpt
end
And then in the controller
def create
@blogpost = Blogpost.new(blogpost_params)
@blogpost.excerpt_setter = truncate(@excerpt.body, :length => 114)
respond_to do |format|
if @blogpost.save
etc,etc,
end
Another thing: You can also define a excerpt
method in your model and drop the field if there isnt any good reason to store a part of the body in another field.
include ActionView::Helpers::TextHelper # this is needed to make the truncate method avaiable in model
...
...
...
def excerpt
truncate(self.body, :length => 114)
end
If you dont need the data stored in the database for performence reasons this whould be my prefered solution.
Upvotes: 1