Find 返回枚举器,而不是对象
我正在开发一个 Rails 3 应用程序,我的一个控制器中有一行,如下所示:
@features = Feature.find(:all, :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
@feature = @features.find(params[:feature])
这个想法是从数据库中获取一组“功能”,受到一些约束,然后选择从那组中特别拿出一个。如果相关记录存在于数据库中但不符合约束,我不想返回它。因此,我正在执行 @features.find
而不是 Feature.find
。
我遇到的问题是视图需要 @feature.title
,这会生成错误:
undefined method 'title' for #<Enumerator:0x0000010216efd8>
当然,我可以通过用此替换上面的内容来回避问题,我只需定义约束两次:
@features = Feature.find(:all, :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
@feature = Feature.find(params[:feature], :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
但这看起来不优雅而且有点多余。
最好的解决方案是什么?如何将我的 @features.find
结果视为 Feature
本身,而不是缺少我需要的变量/方法的 Enumerator
在视图中访问?
感谢您对此的任何想法。
I'm working on a Rails 3 app, and I've got a line in one of my controllers that looks as follows:
@features = Feature.find(:all, :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
@feature = @features.find(params[:feature])
The idea is to grab a set of "features" from the DB, subject to some constraints, and then pick out one in particular from that set. If the record in question exists in the DB but doesn't fit the constraints, I do NOT want to return it. Thus I'm doing @features.find
rather than Feature.find
.
The problem I'm having is that the view needs @feature.title
, which is generating an error:
undefined method 'title' for #<Enumerator:0x0000010216efd8>
Of course, I can sidestep the problem by replacing the above with this, where I simply define the constraints twice:
@features = Feature.find(:all, :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
@feature = Feature.find(params[:feature], :conditions => ['featured_at < ?', Time.current], :order => 'featured_at ASC')
But this seems inelegant and a bit redundant.
What's the best solution? How can I get my @features.find
result treated as the Feature
it is, rather than an Enumerator
that lacks the variables/methods I need to access in the view?
Thanks for any thoughts on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议这样做:
其中
feature_id
是您想要从集合中提取的 id(或 id 列表)。只有第二行会访问数据库。问题在于:all
选项强制该方法发送查询并返回一个数组。I'd suggest this:
where
feature_id
is the id (or list of ids) that you want to pull out of the set. Only the second line will hit the database. The problem is that the:all
option forces the method to send the query and return an array.