How can I make named_scope in Rails return one value instead of an array?

Posted by sameera207 on Stack Overflow See other posts from Stack Overflow or by sameera207
Published on 2010-05-29T07:00:53Z Indexed on 2010/05/29 7:22 UTC
Read the original article Hit count: 359

Filed under:
|
|
|

I want to write a [named scope] to get a record from its id.

For example, I have a model called Event, and I want to simulate Event.find(id) with use of named_scope for future flexibility.

I used this code in my model:

named_scope :from_id, lambda { |id| {:conditions => ['id= ?', id] } }

and I call it from my controller like Event.from_id(id). But my problem is that it returns an array of Event objects instead of just one object.

Thus if I want to get event name, I have to write

event = Event.from_id(id)
event[0].name

while what I want is

event = Event.from_id(id)
event.name

Am I doing something wrong here?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby