我有一个应用程序,可以从输入到模型中的正文文本创建文本摘录,但似乎工作正常,除非出于某种原因,当我尝试在正文中输入一个特定的字符串时。
在我的blog_post模型中我有
t.string "excerpt", limit: 114
在我的控制器中我通过这样做来创建摘录字符串:
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
这似乎在大多数情况下工作正常,但我输入以下文本作为测试
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.
(抱歉有点长)我收到以下错误:
ActiveRecord::StatementInvalid in MoansController#create
Mysql2::Error: Data too long for column 'excerpt' at row 1....
看起来截断是因为某些原因而无法正常工作..是否与此文本有关或者我错过了其他内容?
答案 0 :(得分:1)
我认为您应该删除数据库限制并使用默认情况下截断为所需长度的setter来处理此问题。在您的模型中,将excerpt_setter
添加到attr_accessible
列表中。然后像这样定义它
def excerpt_setter=(str)
self.excerpt = truncate(str, :length => 114)
end
def excerpt_setter
self.excerpt
end
然后在控制器中
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
另一件事:您还可以在模型中定义excerpt
方法,如果没有任何理由将身体的一部分存储在另一个字段中,则删除该字段。
include ActionView::Helpers::TextHelper # this is needed to make the truncate method avaiable in model
...
...
...
def excerpt
truncate(self.body, :length => 114)
end
如果出于性能原因不需要存储在数据库中的数据,那么这将是我首选的解决方案。