Find 返回枚举器,而不是对象

发布于 2024-11-16 05:42:57 字数 1016 浏览 1 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一口甜 2024-11-23 05:42:57

我建议这样做:

@features = Feature.where('featured_at < ?', Time.now).order('featured_at ASC')
@feature = @features.find(feature_id)

其中 feature_id 是您想要从集合中提取的 id(或 id 列表)。只有第二行会访问数据库。问题在于 :all 选项强制该方法发送查询并返回一个数组。

I'd suggest this:

@features = Feature.where('featured_at < ?', Time.now).order('featured_at ASC')
@feature = @features.find(feature_id)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文