开发者

Find is returning Enumerator, not object

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开发者_如何学Go < ?', 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜