简体   繁体   中英

querying active record

i am trying to query my postgres db from rails with the following query

    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.

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. 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. 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. 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. This prevents unnecessary queries. ActiveRecord is able to do this because they return Relations, instead of the queried objects. The best way to think of the Relation class is that it is an instance of ActiveRecord with all the methods of an array. 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.

Just retrieve first record with .first, this might help. User.where("manager <> 0 AND team_id == :team_id", {:team_id => team.id}).first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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