Rails:如何以特定方式命名模型的属性?

时间:2010-07-22 09:58:19

标签: ruby-on-rails model attributes rename

我正在寻找解决我的小问题 - 也许你想帮助^^

我在Ruby on Rails中建模了“Person”和“Contact”类。一个人可以有很多联系人,联系人可以有一个特定的人,并用值

描述这种关系
class Person < ActiveRecord::Base
  has_many :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :person
  has_one    :person #how to rename this?
end

在Person的表中没什么特别的,或者联系的相关列,但是联系表脚本看起来像这样

class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.references :person
      t.references :person #how to rename this eather?
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end

正如我在源代码中写的那样 - 我不知道如何将第二个关系重命名为person - 如果你能给我一个提示我将非常感激=)

问候 KLAF

4 个答案:

答案 0 :(得分:1)

class Person < ActiveRecord::Base
  has_many :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :person
  belongs_to :contact, :class_name => "Person"
end

#in migration
class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.references :person
      t.integer    :contact_id
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end

答案 1 :(得分:0)

这个怎么样:

class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.references :person
      t.string     :person_description
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end

从联系人中删除has_one :person

获取说明:

some_contact.person_description

答案 2 :(得分:0)

我将:belongs_to重命名为'owner',并将:has_one保留为'person'。

答案 3 :(得分:0)

您的has_one x模型中不需要额外的Contact关系,因为由于belongs_to :person关联,已存在隐式的1-1关系。

请注意,您的contacts表应该有一个person_id整数字段作为外键。