Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 5-如何从数组转换为activerecord关系?_Ruby On Rails_Arrays_Ruby_Activerecord - Fatal编程技术网

Ruby on rails Rails 5-如何从数组转换为activerecord关系?

Ruby on rails Rails 5-如何从数组转换为activerecord关系?,ruby-on-rails,arrays,ruby,activerecord,Ruby On Rails,Arrays,Ruby,Activerecord,在rails 5中,我编写了一个类似于User.where(“id=#{current_User.id}”).include_associations.order(created_at::desc) 这将返回一个类似于[#]的列表 如何在此处仅获取activerecord数据(不需要数组)? 我想要一个类似于#的列表。您有两个选择 将.first添加到查询中 使用User.find(当前用户id). 您还需要列表,然后必须迭代数组 users = User.where("id = #{curre

在rails 5中,我编写了一个类似于
User.where(“id=#{current_User.id}”).include_associations.order(created_at::desc)

这将返回一个类似于
[#]
的列表

如何在此处仅获取activerecord数据(不需要数组)? 我想要一个类似于
#
的列表。您有两个选择

  • .first
    添加到查询中

  • 使用
    User.find(当前用户id).


  • 您还需要列表,然后必须迭代数组

    users = User.where("id = #{current_user.id}").include_associations.order(created_at: :desc)
    users.each do |user|
      #user is activerecord data here
    end
    

    如果您只需要当前用户的关联,并且您已经正确设置了“has_many”,那么您可以

    current_user.associations.order(created_at: :desc)
    
    这将为您提供所有关联记录,并且(当然)当前用户信息(如
    id
    name
    )可直接从当前用户处获得


    这将是一个ActiveRecord::关系,您可以对其进行迭代,因此,是的,它的行为将类似于一个数组。如果需要所有列表,则需要数组或类似数组的结构

    这里有一个供您选择的方法,例如-

     user_array = User.where("id = #{current_user.id}").include_associations.order(created_at: :desc)
    active_record_of_users = User.where(id: user_array.map(&:id))
    

    .where
    返回一个表示结果集合的关系,因为在
    .where
    条件下通常可能有0个或多个结果。activerecord实例只是一个结果。你想要什么?仅是
    where
    的第一个结果?在这种情况下,只需编写
    User.where(…)。首先
    ,或者使用
    。查找
    而不是
    。where
    。如果您希望多个ActiveRecords中的每一个一次都有一个,只需在
    之后使用
    。顺序(…)
    语句。我希望所有列表不是一行。@ShruthiR所有列表不能表示为单个ActiveRecord。所以您的原始问题不清楚。您无法检索非数组的列表。如果您需要多个记录,则会有一个记录数组。