Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save karmi/5564 to your computer and use it in GitHub Desktop.
Save karmi/5564 to your computer and use it in GitHub Desktop.
# artist.rb
class Artist < ActiveRecord::Base
has_many :works
has_many :compositions, :through => :works
end
# composition.rb
class Composition < ActiveRecord::Base
has_many :works
has_many :artists, :through => :works
end
# work.rb
class Work < ActiveRecord::Base
set_table_name :artist_works # We really want to reflect the association somehow in the database
belongs_to :artist
belongs_to :composition
end
# -- script/console
>> a = Artist.first
=> #<Artist id: 1, first_name: "Bedřich", middle_name: nil, last_name: "Smetana", description: "Hudební skladatel a dirigent.", text: "Bedřich Smetana (2. března 1824 Litomyšl – 12....", nationality: "Česká Republika", published: true, created_at: "2008-08-15 10:41:57", updated_at: "2008-08-15 10:41:57">
>> a.compositions.first
=> #<Composition id: 1, title_cs: "Má vlast", title_en: "My Country", title_de: "Mein Vaterland", created_at: "2008-08-15 10:41:57", updated_at: "2008-08-15 10:41:57">
>> c = Composition.first
=> #<Composition id: 1, title_cs: "Má vlast", title_en: "My Country", title_de: "Mein Vaterland", created_at: "2008-08-15 10:41:57", updated_at: "2008-08-15 10:41:57">
>> c.artists
=> [#<Artist id: 1, first_name: "Bedřich", middle_name: nil, last_name: "Smetana", description: "Hudební skladatel a dirigent.", text: "Bedřich Smetana (2. března 1824 Litomyšl – 12....", nationality: "Česká Republika", published: true, created_at: "2008-08-15 10:41:57", updated_at: "2008-08-15 10:41:57">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment