2014-01-17 45 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

我去了第二個選擇定義在模型中的摘錄..我認爲我過去使事情變得複雜 –

相關問題