How can I make named_scope in Rails return one value instead of an array?
In this case I'd create a class method
def self.from_id(id) self.find(id).firstend
Another example:
class Invoice def self.number self.find(:first, :select => "max(number) As last, max(number)+1 As next", :conditions => "type = 'SalesOrder'") endend
Methods like this its better then named_scope. You can call Invoice.number.next
, better than named_scope
return Invoice.number[0].next
.
As Damien mentions, using a custom scope just to look up by ID isn't advisable. But to answer your question:
Finding records with named_scope
will always return an ActiveRecord::NamedScope::Scope
object, which behaves like an array. If there is just a single record returned by your query, you can use the first
method to get the ActiveRecord object directly, like this:
event = Event.from_id(id).firstevent.name # will work as you expect
There's no need to use a scope here. You could just do Event.find_by_id id
.
The difference between find
and find_by_id
is that the first one will raise an ActiveRecordNotFoundException
if the record does not exist. The second one will just return nil.
Writing a scope to get the record by it's id is a very bad id as it is something which is already provided natively by rails.