问题
Take for example this situation.
You have 3 models:
- Poet - Represents the author of a poem
- Poem - Represents a poem written by a Poet
- Printing - Represents a printed publication of any sort containing the Poet's Poem.
Right off the bat poet and poem are obvious:
- Poet
has_many
poems - Poem
belongs_to
poet
It becomes confusing for me when dealing with the Printing model.
In this case a Printing, in some sense, belongs to both the poet and poem. You could say a poet has_many printings or a poem has_many printings which makes sense but going the inverse route is tricky...
What about a situation where some magazine or book printed 5 poems from one poet? OR, one of the poems is published in 10 different magazines?
It almost seems as if the Printing itself "belongs to many" poems or poets. I know this is wrong, but i'm just trying to articulate the point.
So the answerable question is this: How would you set up these relationships? Specifically, what would the model and database table look like AND how would you use them to access associated data?
Thank you!
回答1:
What about a situation where some magazine or book printed 5 poems from one poet?
Remeber if you have a poet that has many poems and printing that has many poems as well you can alway get the poet.
Poet.poems.first.printings would return all the printings of the poets first poem
or you could do Printing.poems.first.poet This way you could get the poet of the first poem in the printing.
How would you set up these relationships? Specifically, what would the model and database table look like AND how would you use them to access associated data?
I would set it up like this
Poet :has_many poems
poem :belongs_to poet
poem :has_and_belongs_to_many printings
printing :has_many poems
Because you are using a has_and_belogs_to_many association you need a join table, for poems and printings
you would have migration that looks like this
CreatePoemsPrintingJoinTable < ActiveRecord::Migration
def self.up
create_table :poems_printings, :id => false do |t|
t.integer :poem_id
t.integer :printing_id
end
end
def self.down
drop_table :poems_printings
end
end
The other tables are pretty easy
CreateTablePoems < ActiveRecord::Migration
def self.up
create_table :poems, do |t|
t.integer :poet_id
end
end
def self.down
drop_table :poems
end
end
CreateTablePoets < ActiveRecord::Migration
def self.up
create_table :poets do |t|
end
end
def self.down
drop_table :poems
end
end
CreateTablePrintings < ActiveRecord::Migration
def self.up
create_table :printings do |t|
end
end
def self.down
drop_table :printings
end
end
来源:https://stackoverflow.com/questions/6970047/question-on-proper-associations-in-rails