简体   繁体   中英

Rails Active Model Association Issue

I am having an issue with model associations. I want to pull a route's trip info by accessing the data from trips.route_id where routes.route_id would be the same value. Currently the SQL query is calling routes.id , instead using routes.route_id . Any help would be appreciated.

Route Table Structure

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

The primary_key on this table is 'id'.

Models

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

Route Controller

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

Want to call @route.trips to pull trip information associated with said @route

LOG INFO

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

Trip Load Explanation: 15 represents the id of the object returned from the "Route Load" query. I would like to use the routes.route_id value of the result instead of the id to build the "Trip Load" query.

Desired result:
Trip Load (8.4ms) SELECT 'trips'.* FROM 'trips' WHERE 'trips'.'route_id' = '2-36' ( '2-36' value is referenced from Route Table Structure example)

If I understand your question properly, you need to change your models to something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM