Question

I've searched and found a few things related to this but can't seem to get a working solution out of the posts.

My situation: I have Users and I have Carpools; a User may be a driver of a carpool ( a carpool may only have one driver ) or a User may be a rider in a carpool (a carpool may have multiple riders)

Here is my latest attempt:

class Carpool < ActiveRecord::Base
  attr_accessible :rider_id

  belongs_to :driver, class_name: "User", foreign_key: "driver_id"

  has_many :riders, class_name: "User"

  def add_rider(user)
    self.riders << user 
  end
end

And the User

class User < ActiveRecord::Base
  attr_accessible :driver_id

  has_many :carpools

  belongs_to :carpool, class_name: "Carpool", foreign_key: "rider_id"

end

Relevant Schema Dump:

create_table "users", :force => true do |t|
  t.string   "email",                  :default => "", :null => false
  t.string   "name"
  t.integer  "driver_id"
end

create_table "carpools", :force => true do |t|
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
  t.integer  "rider_id"
end

I think I may be doing something wrong with the foreign keys... The fact that relationship works "backwords" between drivers/carpools [ driver has_many :carpools ] and riders/carpools [carpool has_many :riders] is also fogging up my brain.

What am I doing wrong what's the best way to get this done ?

Any help is much appreciated, thanks!

Was it helpful?

Solution

As per convo's on #rubyonrails, this approach may work for you (Thanks bricker for the gist):

class Carpool
  belongs_to :driver, class_name: "User" # Single Driver per Carpool

  has_many :carpool_riders
  has_many :riders, through: :carpool_riders

  # Schema:
  # driver_id
end
class CarpoolRider
  belongs_to :carpool
  belongs_to :rider, class_name: "User"

  # Schema:
  # carpool_id
  # rider_id
end
class User
  has_many :carpools_driven, class_name: "Carpool", foreign_key: "driver_id"

  has_many :carpool_riders
  has_many :carpools_ridden, through: :carpool_riders
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top