[英]Undefined method sort_by in rails
我在演示者和控制器中使用sort或sort_by時遇到問題。 它說未定義的方法'sort_by'。
它屬於任何特定類別嗎? 我已經在網上查詢過,但是找不到任何具體的東西。
有人可以闡明這一點嗎?
這是我的主持人代碼-
def sortDocument()
@list.sort do |a, b|
(b.published_date <=> a.published_date) ||
a.display_name <=> b.display_name
@list
end
或者
def sortDocument()
@list.sort_by!{ |m| m.published_date }
end
編輯:
錯誤信息:
undefined method `sort_by!' for #<DocumentsBureauServices::DocumentList:0x007ff8250f8a28>
主持人-
class DocumentPresenter
def initialize(list)
@list = list
@list = sort_document()
end
def sortDocument()
@list.sort do |a, b|
(b.published_date <=> a.published_date) ||
a.display_name <=> b.display_name
@list
end
end
或者
def sortDocument()
@list.sort_by!{ |m| m.published_date }
end
使用通過將枚舉中的值映射到給定塊中而生成的一組鍵對枚舉進行排序...以使用sort_by ...
%w{ apple pear fig }.sort_by {|word| word.length}
#=> ["fig", "pear", "apple"]
看起來DocumentsBureauServices::DocumentList
不包含可枚舉的模塊,並且無法訪問sort_by方法。
如果確實DocumentList是可枚舉對象周圍的裝飾器,則可以使用委托器。 ActiveSupport具有專用於委派的方法: http ://apidock.com/rails/Module/delegate
在您的情況下,可以這樣使用它:
class DocumentsBureauServices::DocumentList
delegate :sort_by!, to: :my_enumerable
def initialize(enumerable)
@my_enumerable = enumerable
end
end
然后您可以調用sort_by! 在您的列表對象上,如下所示:
@list = DocumentsBureauServices::DocumentList.new(Document.all)
@list.sort_by! {|m| m.published_date}
#=> [#Document1, #Document2, etc]
如果您想了解更多有關創建自己的演示者的信息,我是否可以推薦出色的RailsCast http://railscasts.com/episodes/287-presenters-from-scratch
我個人將Draper庫用於演示者: https : //github.com/drapergem/draper ,使ActiveRecord對象的演示變得輕而易舉。 此處有一個RailsCast: http ://railscasts.com/episodes/286-draper
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.