我有点困惑,包含是如何工作的。
我对数据库有以下查询:@car = Car.includes(:colors).paginate(:per_page => 10, :page => params[:page]) 在表 Car 中,我有以下列:名称、价格、颜色... 在表颜色列中:car_id、name、color_name、...
在我看来,我可以使用 @car.price 打印汽车价格,但不能使用 @car.color_name,为什么?
另一个问题 - 我在两个表中都有名为 have 的列,我如何知道我当前正在使用哪一个表?如果我将@car.name,那么该值将从汽车表或颜色中获取?
我很抱歉问了一个愚蠢的问题,但我不知道如何处理两个表中的数据。
最佳答案
假设这是一个 Car has_many
Colors 关联,它看起来像这样:
# 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
当您使用includes
语句时,这并不意味着两个模型会相互混合。关联只是预加载的,但共轨关联结构仍然相同...希望这有帮助:)
关于mysql - Rails 3 - 在查询中包含值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979770/