如何限制使用 Sequel 和 Ruby 查询返回的字符数?
我的模型是 Article
,我想仅显示文章正文的一个片段,以预览这篇特定文章。
我该如何用续集做到这一点?
我认为它可能使用 limit
,但这只是限制从数据库返回的记录数。
理想情况下,我想做类似的事情: Article.first.limit(40)
其中 40 是前 40 个字符。
我知道 limit
不起作用,但我只是用它作为示例来说明我正在寻找的内容。
编辑1:
我正在使用Sinatra。我想限制返回值,但来自视图,而不是路由文件。
我在路由文件中做了类似的事情:
@section = HelpSections.filter(:type => 'a').order(:sort, :name)
这给了我一个 a
类型的所有部分的列表。
然后,转到我做的一篇文章:
@section.each do |article|
article.question.each do |title|
title.name[0..9]
end
end
基于这种情况,我想做的是限制返回的“名称”属性的大小。
但是,当我这样做时,我收到此错误:
undefined method '[]' for nil:NilClass
如何处理此问题,以便限制 name
属性的大小?
My model is Article
, and I want to display just a snippet of the body of the article, to give a preview of this particular article.
How would I do that with Sequel?
I thought it might be using limit
, but that just limits the number of records returned from the db.
Ideally I would like to do something like: Article.first.limit(40)
where 40 is the first 40 characters.
I know limit
won't work, but I am just using it as an example to illustrate what I am looking for.
Edit 1:
I am using Sinatra. I wanted to restrict the returned values but from the view, rather than the routing file.
I do something like this in the routing file:
@section = HelpSections.filter(:type => 'a').order(:sort, :name)
Which gives me a list of all sections of type a
.
Then, to get to an article I do:
@section.each do |article|
article.question.each do |title|
title.name[0..9]
end
end
Based on this scenario, what I want to do is restrict the size of the 'name' attribute returned.
But, when I do that, I get this error:
undefined method '[]' for nil:NilClass
How do I handle this, so that I can restrict the size of the name
attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
难道你不只是做这样的事情吗?:
如果你真的需要通过SQL来做,你可以做这样的事情:(
你可能必须使用
.substring
代替substr< /code> 取决于您的数据库)
Could you not just do something like this?:
If you really need to do it through SQL, you can do something like this:
(You may have to use
.substring
in place ofsubstr
depending on your DB)