2014-01-17 43 views
1

我有一个应用程序,可以从输入到模型中的正文文本创建文本摘录,它似乎能正常工作,除了某些原因,当我尝试输入一个特定的字符串正文文本。Rails截断后的“列数据太长”错误

在我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

这个列是如何在MySQL中定义的?那里的最大长度是多少? –

+0

您使用的是哪个版本的Rails? –

+0

它的轨道4和用于添加列的迁移是add_column(:blogposts,“摘录”,:字符串,:极限=> 114) –

回答

1

我想你应该删除数据库限制,并通过使用一个setter来处理,默认情况下这个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 

如果你不需要存储在数据库性能自动原因,这个数据是对子级首选我的解决方案。

+0

谢谢大卫 - 那对我很好用 –

+0

哪个解决方案? – davidb

+0

我去了第二个选择定义在模型中的摘录..我认为我过去使事情变得复杂 –

相关问题