Leem.fin
Leem.fin

Reputation: 42652

Rails way to COUNT the nr of records in my case

I am using Rails v2.3.2.

I have a model called UsersCar:

class UsersCar < ActiveRecord::Base
  belongs_to :car
  belongs_to :user
end

This model mapped to a database table users_cars, which only contains two columns : user_id, car_id.

I would like to use Rails way to count the number of car_id where user_id=3. I konw in plain SQL query I can achieve this by:

SELECT COUNT(*) FROM users_cars WHERE user_id=3;

Now, I would like to get it by Rails way, I know I can do:

UsersCar.count()

but how can I put the ...where user_id=3 clause in Rails way?

Upvotes: 1

Views: 5537

Answers (4)

Wahaj Ali
Wahaj Ali

Reputation: 4113

If you have the User object, you could do

user.cars.size 

or

user.cars.count

Another way would be to do:

UserCar.find(:user_id => 3).size

And the last way that I can think of is the one mentioned above, i.e. 'UserCar.count(conditions)'.

Upvotes: 3

Leem.fin
Leem.fin

Reputation: 42652

I managed to find the way to count with condition:

UsersCar.count(:condition=>"user_id=3")

Upvotes: 0

Limbo Peng
Limbo Peng

Reputation: 2505

According to the Ruby on Rails Guides, you can pass conditions to the count() method. For example:

UsersCar.count(:conditions => ["user_id = ?", 3])

will generates:

SELECT count(*) AS count_all FROM users_cars WHERE (user_id = 3)

Upvotes: 4

berkes
berkes

Reputation: 27603

With the belogngs to association, you get several "magic" methods on the parent item to reference its children.

In your case:

users_car = UsersCar.find(1) #=>one record of users_car with id = 1.
users_car.users              #=>a list of associated users.
users_car.users.count        #=>the amount of associated users.

However, I think you are understanding the associations wrong, based on the fact that your UsersCar is named awkwardly.

It seems you want

  • User has_and_belongs_to_many :cars
  • Car has_and_belongs_to_manu :users

Please read abovementioned guide on associations if you want to know more about many-to-many associations in Rails.

Upvotes: 1

Related Questions