Question on Proper Associations in Rails

孤街醉人 提交于 2019-12-11 08:34:44

问题


Take for example this situation.

You have 3 models:

  1. Poet - Represents the author of a poem
  2. Poem - Represents a poem written by a Poet
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!