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 开发者_如何学JAVAmy 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.rb
file, 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_method
line:
helper_method :shorten
def shorten(theString, length = 50)
if theString.length >= length
shortened = theString[0, length]
else
theString
end
end
Lastly, if you want to be able to apply this directly to a model, put it in your app/models/posts.rb
file instead (without the helper_method
line). However, I assume that rather than passing it a string, you'd just want to use one of your fields:
def shorten(length = 50)
if description.length >= length
description[0, length]
else
description
end
end
Then you can call it like this:
<%= post.shorten %>
However, Rails already has a truncate method build in that you could use instead:
<%= truncate("My really long string", :length => 50) %>
精彩评论