2010-07-22 28 views
1

我正在尋找我的小問題的解決方案 - 也許你想要幫助^^Rails:如何以特定方式命名模型的屬性?

我在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 

在人的表這種關係是沒有什麼特別的,或列相關接觸,但接觸的表腳本看起來是這樣的

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 

,因爲我在源代碼編寫 - 我不知道如何重新命名的第二個關係人 - 如果你可以給我一個提示,我會非常感謝=)

問候 Klaf

回答

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 
0

我會重新命名:belongs_to的爲 '主人',並留下了:HAS_ONE爲 '人'。

0

您的Contact模型中不需要額外的has_one x關係,因爲由於belongs_to :person關聯存在隱含的1-1關係。

請注意,您的contacts表應該有一個person_id整數字段作爲外鍵。

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 
相關問題