Ruby on rails 铁路";数据对于“列”太长;截断后的错误

Ruby on rails 铁路";数据对于“列”太长;截断后的错误,ruby-on-rails,exception,controller,truncate,Ruby On Rails,Exception,Controller,Truncate,我有一个应用程序,可以从输入到模型中的正文文本中创建文本摘录,它似乎工作得很好,但出于某种原因,当我尝试在正文文本中输入一个特定字符串时除外 在我的博客文章模型中,我有 t.string "excerpt", limit: 114 在我的控制器中,我通过以下操作创建摘录字符串: def create @blogpost = Blogpost.new(blogpost_params) @excerpt = @blogpost.body @blogpost.e

我有一个应用程序,可以从输入到模型中的正文文本中创建文本摘录,它似乎工作得很好,但出于某种原因,当我尝试在正文文本中输入一个特定字符串时除外

在我的博客文章模型中,我有

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....

由于某种原因,截断似乎不起作用。。是与此文本有关还是我遗漏了其他内容?

我认为您应该删除数据库限制,并使用默认情况下截断为所需长度的setter来处理此问题。在您的模型中,将摘录设置器添加到可访问的属性列表中。然后像这样定义它

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
另一件事:您还可以在模型中定义
extract
方法,如果没有任何好的理由将身体的一部分存储在另一个字段中,则可以删除该字段

include ActionView::Helpers::TextHelper  # this is needed to make the truncate method avaiable in model

...
...
...

def excerpt
  truncate(self.body, :length => 114)
end

如果出于性能原因,您不需要存储在数据库中的数据,这将是我首选的解决方案。

MySQL中如何定义此列?最大长度是多少?您使用哪个版本的Rails?它是Rails 4,用于添加列的迁移是add_column(:blogposts,“extract”,:string,:limit=>114)尝试截断到111characters@IvanDenisov这不应该是一个问题。
:limit=>114
确实将
包含在限制计数中。哪种解决方案?我选择了在模型中定义摘录的第二个选项。。我想我以前把事情复杂化了