Currently I'm using .build in my Create action so that I have a little
more control before it gets saved. For instance, I have:
@comment = current_user.comments.build(params[:comment])
@comment.blog_comment = @comment.blog_comment[0...140]
to chop the blog_comment off at 140 characters. Well, that works
great, but if a user goes to edit that comment, they can then make the
comment longer than 140 characters since I'm using the following in
the update action:
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
So, how do I interject and chop off the comment at 140 characters when
a user decides to update their comment?
One way might be to alter the value first with something like:
@comment = Comment.find(params[:id]
comment_attributes = params[:comment]
comment_attributes['blog_comment'] &&=
comment_attributes['blog_comment'][0...140]
if @comment.update_attributes(comment_attributes)
Something similar could also be done in the create case, in which case
I'd factor out the two lines calculating comment_attributes into a
controller method.
Seems like the perfect place for a call back if you're doing this
without discriminating.
class Comment < ActiveRecord::Base
...
before_validation :trim_blog_comment
protected
def block_comment
self.blog_comment = blog_comment[0..140] if blog_comment.length >
140
end
end
Now it's being trimmed at the model level on all creates/saves/
updates, no matter where the call to save comes from.
This is perfect! Thank you Emery.
I was thinking the same thing, but was trying before_save filters and
couldn't get it to work for the Update action.
Honestly, I didn't even know about the before_validation helper, guess
I got some more learnin' to do.
Thanks again.
And @Rick, thank you for the suggestion as well.