user1946705
user1946705

Reputation: 2888

Rails 3 - include value in query

I am a bit confused, how works include.

I have this query to database: @car = Car.includes(:colors).paginate(:per_page => 10, :page => params[:page]) In table Car I have columns: name, price, color, ... In table Colors columns: car_id, name, color_name, ...

In my view I can use for printing price of the car @car.price, but I can't use @car.color_name, why?

And the another problem - I have in both tables the column called have, how I will to know, with which one I am working currently? If I will do @car.name, so this value will be take from Cars table or Colors?

I am sorry for maybe stupid question, but I don't know, how to work with the data from 2 tables.

Upvotes: 0

Views: 166

Answers (1)

chris_b
chris_b

Reputation: 1294

Assuming that this is a Car has_many Colors association it will look something like this:

# This loads 10 cars with offset X
@cars = Car.includes(:colors).paginate(:per_page => 10, :page => params[:page])
# the first car found
@car = @cars.first
# Name of the Car
@car.name
# All colors of the car
@car.colors
# The name of the first color
@car.colors.first.name

When you use the includes statement, this does not mean both models are mixed into each other. The associations are just preloaded, but the common rails association structure is still the same... Hope this helps :)

Upvotes: 1

Related Questions