Skip to content

Instantly share code, notes, and snippets.

@jcquarto
jcquarto / gist:6197313
Last active December 20, 2015 21:28
has_many through consistently causes me to re-think what it all means. Here's a useful example plus accompanying rspec tests
English: a User manages many Listings, and a Listing is managed by many Users. The association is handled by ListingManager via listing_id and manager_id as foreign keys.
In the examples, below notice how one can create willy-nilly method names for the association as long as one defines how to get from one side of the association to the other. Another take away: the info for class_name and foreign_key and source are handled as literal strings for the purposes of the method constructing its SQL behind the scenes; it's only where Rails cannot infer the naming that one has to help out a bit
class ListingManager < ActiveRecord::Base
belongs_to :listing
belongs_to :manager, class_name:"User"
belongs_to :cato, class_name:"User", foreign_key: "manager_id"
end