0

您好我有三個表如下所示:的has_many關係導軌3

class Workitem < ActiveRecord::Base 
     has_many :effort 
     attr_protected 
    end 

    class Effort < ActiveRecord::Base 
     attr_protected 
     belongs_to :workitem 
     belongs_to :person 
    end 

    class Person < ActiveRecord::Base 
     attr_accessible :given_name, :mgrid, :surname, :id 
     has_many :effort 
    end 

的想法是跟蹤有多少天一個人通過努力桌上,花了一個特定的工作項目。有人可以驗證我的關係是否正確嗎?但這似乎並不奏效。我在這裏錯過了什麼嗎? 另外,我無法理解has_many :through種類的關聯。如果這是我在這種情況下應該使用的,有人可以給我一個想法嗎?

回答

1

你會通常有孩子的複數對象:

class Workitem < ActiveRecord::Base 
    has_many :efforts 
    attr_protected 
end 

class Person < ActiveRecord::Base 
    attr_accessible :given_name, :mgrid, :surname, :id 
    has_many :efforts 
end 

而且我建議使用attr_accessible代替attr_protected

如果一個Foo有許多酒吧和酒吧屬於許多FOOS,它可能看起來像這樣:

class Foo < ActiveRecord::Base 
    has_many :foo_bar 
    has_many :bars, through => :foo_bar 
end 

class Bar < ActiveRecord::Base 
    has_many :foo_bar 
    has_many :foos, through => :foo_bar 
end 

class FooBar 
    belongs_to :foo 
    belongs_to :bar 
end 

反正就是這樣。 Railcasts here

還有一些幫助,還有一萬億個例子。

希望有幫助

+1

嗨@simonmorley 謝謝你的回覆。我將我的孩子名稱改爲複數。但是,我有另一個錯誤,說明effort.person_id不存在。 這是當我從IRB嘗試以下內容時:> p = Person.find 1234 > p.efforts ActiveRecord :: StatementInvalid:PG :: Error:ERROR:列effort.person_id不存在 我是否再次出錯? :( – anipendakur

+0

有創建和運行遷移?而且,你應該使用的軌道C未IRB從您的項目中。 – simonmorley

+0

嗨,我跑我的遷移。我很抱歉,我的意思是說軌道控制檯,不IRB。我的錯誤。當我在Effort.column_names在控制檯中我得到的列名類型,但它不顯示任何外鍵(workitem_id,爲person_id)。我需要這些列在另一遷移單獨添加到工作表? – anipendakur