我对模型关联有疑问。我想通过访问trips.route_id中的数据来提取路线的行程信息,其中route.route_id将是相同的值。当前,SQL查询正在调用routes.id,而不是routes.route_id。任何帮助,将不胜感激。

路由表结构

COLUMNS: id,route_id,route_short_name,route_long_name,route_desc,route_type
ROW: 1,2-36,2,"East 34th St",,3


该表上的primary_key是'id'。

楷模

class Route < ActiveRecord::Base
  has_many :trips, :foreign_key => 'route_id'
end


class Trip < ActiveRecord::Base
  belongs_to :route
end


路线控制器

class RouteController < ApplicationController
  def show
    @route = Route.where("'%s' = routes.route_short_name",params[:id]).first
  end
end


要呼叫@route.trips提取与所述trip相关的@route信息

日志信息

Started GET "/route/19" for 127.0.0.1 at Wed Nov 23 21:09:55 -0500 2011
Processing by RouteController#show as HTML
Parameters: {"id"=>"19"}
Route Load (0.4ms)  SELECT `routes`.* FROM `routes` WHERE ('19' = routes.route_short_name) LIMIT 1
Trip Load (8.4ms)  SELECT `trips`.* FROM `trips` WHERE `trips`.`route_id` = 15


跳闸负载说明:15表示从“路由负载”查询返回的对象的id。我想使用结果的routes.route_id值而不是id来构建“旅行负荷”查询。

所需结果:
 Trip Load (8.4ms) SELECT 'trips'.* FROM 'trips' WHERE 'trips'.'route_id' = '2-36'
'2-36'值从路由表结构示例中引用)

最佳答案

如果我正确理解了您的问题,则需要将模型更改为以下形式:

class Route < ActiveRecord::Base
  has_many :trips, :primary_key => "route_id"
end

class Trip < ActiveRecord::Base
  belongs_to :route, :primary_key => "route_id"
end

10-01 12:15