【问题标题】:Rails 3 - include value in queryRails 3 - 在查询中包含值
【发布时间】:2011-08-08 08:59:36
【问题描述】:

我有点困惑,包括是如何工作的。

我对数据库有以下查询:@car = Car.includes(:colors).paginate(:per_page => 10, :page => params[:page]) 在表 Car 我有列:名称,价格,颜色,... 在表 Colors 列中:car_id、name、color_name、...

在我看来,我可以使用 @car.price 打印汽车的价格,但我不能使用 @car.color_name,为什么?

另一个问题 - 我在两个表中都有名为 have 的列,我将如何知道我目前正在使用哪一个?如果我会执行 @car.name,那么这个值将从 Cars 表或 Colors 中获取?

我很抱歉这个问题可能很愚蠢,但我不知道如何处理来自 2 个表的数据。

【问题讨论】:

  • 将模型代码添加到问题中。这似乎是一个简单的问题,但我需要更多信息来帮助你

标签: mysql ruby-on-rails-3 model include


【解决方案1】:

假设这是一个 Car has_many 颜色关联,它看起来像这样:

# 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 语句时,这并不意味着两种模型相互混合。关联只是预加载的,但公共导轨关联结构仍然相同......希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2021-04-16
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多