我想写一个named scope从它的 id 中获取记录。
例如,我有一个名为 Event
的模型,我想使用 named_scope
来模拟 Event.find(id)
future 的灵 active 。
我在我的模型中使用了这段代码:
named_scope :from_id, lambda { |id| {:conditions => ['id= ?', id] } }
我从我的 Controller 调用它,如 Event.from_id(id)
。但我的问题是它返回一组 Event
对象而不是一个对象。
因此如果我想获取事件名称,我必须写
event = Event.from_id(id)
event[0].name
而我想要的是
event = Event.from_id(id)
event.name
我是不是做错了什么?
最佳答案
在这种情况下,我会创建一个类方法
def self.from_id(id)
self.find(id).first
end
另一个例子:
class Invoice
def self.number
self.find(:first,
:select => "max(number) As last, max(number)+1 As next",
:conditions => "type = 'SalesOrder'")
end
end
像这样的方法比 named_scope 更好。您可以调用 Invoice.number.next
,比 named_scope
返回 Invoice.number[0].next
更好。
关于ruby-on-rails - 如何让 Rails 中的 named_scope 返回一个值而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2934140/