简体   繁体   English

[]:Array的未定义方法`order'

[英]undefined method `order' for []:Array

I have the following code where I load the activities for the user based on whether or not they are an admin. 我有以下代码,可以根据用户是否是管理员来为用户加载活动。 Users can only see their own activity feed, whereas admins can see the entire stream. 用户只能看到自己的活动供稿,而管理员可以看到整个流。 This is a precursor to sharing activity feeds with friends, etc. 这是与朋友等共享活动提要的前提。

  def index
    if current_user?
      @incidents = Incident.find_all_by_user_id(current_user.id).order("created_at desc")
    else
      @incidents = Incident.all.order("created_at desc")
    end
  end

I am getting the above referenced error( undefined method "order" for []:Array ). 我收到了上面引用的错误( undefined method "order" for []:Array )。 It seems to be the .order reference, but I have checked the rails Guides and it seems to be correct syntax. 它似乎是.order参考,但是我检查了rails指南,它似乎是正确的语法。

Any ideas? 有任何想法吗?

Try changing the find_by... to where , so: 尝试将find_by...更改为where ,因此:

def index
    if current_user?
      @incidents = Incident.where(user_id: current_user.id).order("created_at desc")
    else
      @incidents = Incident.all.order("created_at desc")
    end
  end

should work :-) 应该管用 :-)

The #index action method can be simplified and optimized (by replacement find_all_by with where ) to: #index操作方法可以简化和优化(通过将find_all_by替换为where ),以:

 def index
   clause = current_user? && Incident.where(user_id: current_user.id) || Incident
   @incidents = clause.order("created_at desc")
 end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM