I just started working with rails, and I know it must be something simple I’m doing wrong, but for the life of me I can’t figure it out.
I’m trying to define a simple method in my controller for a “post” called “shorten” that will return a shortened version of whatever string I pass to it. In my posts_controller.rb, I put the following;
def shorten(theString, length = 50)
if theString.length >= length
shortened = theString[0, length]
else
theString
end
end
Trying to call it from within my view gives me an undefined method error. I am calling it from within an instance of the post, so I assumed I didn’t need self.shorten. I went ahead and tried prepending self to the method definition anyway and it still didn’t work.
By default, methods defined within your controller are only available to your controller, not your view.
The preferred way to handle this would be to move your method to your
app/helpers/posts_helper.rbfile, then it will work fine in your view.If you need to be able to access the method in both your controller and view though, you can just leave it defined in your controller and add a
helper_methodline:Lastly, if you want to be able to apply this directly to a model, put it in your
app/models/posts.rbfile instead (without thehelper_methodline). However, I assume that rather than passing it a string, you’d just want to use one of your fields:Then you can call it like this:
However, Rails already has a truncate method build in that you could use instead: