Jensky
Jensky

Reputation: 917

Select record from table (and some conditions)

I don't want to use pure sql query but I can't deal with Active Records methods.

I have models like those:

class Car < ActiveRecord::Base
  has_many :reviews
end

and

class Review < AcriveRecord::Base
  belongs_to :cars
end

And now I want get all reviews for specific Car. You know I want to select all records from reviews where car_id is the same (just all reviews for specific car).

I'm trying with http://guides.rubyonrails.org/active_record_querying.html but it still doesn't work.

Upvotes: 0

Views: 60

Answers (3)

RAJ
RAJ

Reputation: 9747

You will be able to get all reviews of a car by:

@car.reviews

Update your review.rb model as:

class Review < AcriveRecord::Base
  belongs_to :car # SINGULAR !
end

It will give you facility to fetch car for a review as:

@review.car

Upvotes: 2

gaurav.singharoy
gaurav.singharoy

Reputation: 3941

This is very straightforward. First get the Active record for car with, say id stored in variable car_id

@car = Car.find(car_id)
@car.reviews #This will get you the reviews

To avoid multiple DB calls, u can use includes

@car = Car.includes(:reviews).find(car_id) 

If you just want the reviews then

@reviews = Review.where(:car_id=>car_id) #provided car_id is the foreign key here

Upvotes: 1

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42919

Just find the car object you want, something like this for example

@car = Car.find(id: params[id])

Then all associations are easily accessed by their names, wihout needing to do a query

@reviews = @car.reviews

Upvotes: 1

Related Questions