简体   繁体   English

查询活动记录

[英]querying active record

i am trying to query my postgres db from rails with the following query 我正在尝试使用以下查询从Rails查询我的postgres数据库

    def is_manager(team)
    User.where("manager <> 0 AND team_id == :team_id", {:team_id => team.id})
  end

this basically is checking that the manager is flagged and the that team.id is the current id passed into the function. 这基本上是在检查是否标记了经理,并且那个team.id是传递给函数的当前ID。

i have the following code in my view 我认为以下代码

 %td= is_manager(team)

error or what we are getting return is 错误或我们得到的回报是

#<ActiveRecord::Relation:0xa3ae51c>

any help on where i have gone wrong would be great 对我出问题的地方的任何帮助都会很棒

Queries to ActiveRecord always return ActiveRecord::Relations. 对ActiveRecord的查询始终返回ActiveRecord :: Relations。 Doing so essentially allows the lazy loading of queries. 这样做实质上允许延迟加载查询。 To understand why this is cool, consider this: 要了解为什么这很酷,请考虑以下因素:

User.where(manager: 0).where(team_id: team_id).first

In this case, we get all users who aren't managers, and then we get all the non-manager users who are on team with id team_id, and then we select the first one. 在这种情况下,我们得到所有不是管理员的用户,然后得到所有ID为team_id的非管理员用户,然后选择第一个。 Executing this code will give you a query like: 执行此代码将给您一个查询,例如:

SELECT * FROM users WHERE manager = 0 AND team_id = X LIMIT 1

As you can see, even though there were multiple queries made in our code, ActiveRecord was able to squish all of that down into one query. 如您所见,即使我们的代码中进行了多个查询,ActiveRecord仍然可以将所有查询压缩为一个查询。 This is done through the Relation. 这是通过关系完成的。 As soon as we need to actual object (ie when we call first), then ActiveRecord will go to the DB to get the records. 只要我们需要实际的对象(即,当我们第一次调用时),ActiveRecord就会转到数据库获取记录。 This prevents unnecessary queries. 这样可以防止不必要的查询。 ActiveRecord is able to do this because they return Relations, instead of the queried objects. ActiveRecord之所以能够执行此操作,是因为它们返回了Relations,而不是查询的对象。 The best way to think of the Relation class is that it is an instance of ActiveRecord with all the methods of an array. 想到Relation类的最好方法是,它是ActiveRecord的实例,具有数组的所有方法。 You can call queries on a relation, but you can also iterate over it. 您可以在关系上调用查询,但也可以对其进行迭代。

Sorry if that isn't clear. 抱歉,如果不清楚。

Oh, and to solve your problem. 哦,解决您的问题。 %td = is_manager(team).to_a This will convert the Relation object into an array of Users. %td = is_manager(team).to_a这将把Relation对象转换为Users数组。

Just retrieve first record with .first, this might help. 只需使用.first检索第一条记录,这可能会有所帮助。 User.where("manager <> 0 AND team_id == :team_id", {:team_id => team.id}).first User.where(“ manager <> 0 AND team_id ==:team_id”,{:team_id => team.id})。first

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

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