Ruby on Rails重命名了外键

时间:2010-01-18 21:50:35

标签: ruby-on-rails

我正在尝试为一本有1位作家和1位艺术家的漫画书创建一个模型。这些都是Person的实例。但是,如何在迁移中显示此内容?

class CreateComics < ActiveRecord::Migration
   def self.up
     create_table :comics do |t|
       t.column :name, :string      
       t.column :writer_id, :integer, :null => false
       t.column :artist_id, :integer, :null => false
     end
   end
...

我怎么说:writer_id应该映射到:person_id还是这种重命名不赞成?

2 个答案:

答案 0 :(得分:4)

使用class_name和foreign_key选项在模型类中创建映射。

belongs_to :writer, :class_name => "Person", :foreign_key => "writer_id"
belongs_to :artist, :class_name => "Person", :foreign_key => "artist_id"

答案 1 :(得分:1)

迁移不知道您打算如何使用其中定义的表。所有这些信息都在模型中。

简而言之,您的移植很适合您所描述的内容。但是你需要充实模型来定义你想要的关联。

class Comic < ActiveRecord::Base
  belongs_to :writer, :class_name => "Person"
  belongs_to :artist, :class_name => "Person"
end

这允许您从漫画中引用作家和艺术家。但是,您可能希望回复该关联,以便您可以根据他们在制作中的角色轻松地从一个人那里获取漫画。

class Person < ActiveRecord::Base
  has_many :comics_as_writer, :class_name => "Comic", :foreign_key => :writer_id
  has_many :comics_as_artist, :class_name => "Comic", :foreign_key => :artist_id

  # some times you don't care what a person did for a comic,
  # you just want to know what they worked on.
  has_many :comics, :finder_sql => "SELECT comics.* FROM comics, people WHERE " +
     "`comics`.`writer_id` = `people`.`id` OR " +
     " `comics`.`artist_id` = `people`.`id`"
end

通过定义这些关系,可以实现以下目标:

@comic.artist # => Person with id matching comics.artist_id
@comic.writer # => Person with id matching comics.writer_id

@person.comics_as_writer # => Array of comics where @person.id matches comics.writer_id
@person.comics_as_artist # => Array of comics where @person.id matches comics.artist_id

@person.comics # => Array of comics where @person.id matches comics.writer_id or comics.artist_id