我有兩個通過has_many/belongs_to關聯的模型。我在子模型中創建了一個類方法。但我無法弄清楚如何從類方法中訪問父模型的實例方法。這裏是什麼,我試圖做一個簡化:如何在Rails中訪問父模型的實例變量?
#User model
class User < ActiveRecord::Base
has_many :addresses
def first_name
"John"
end
def last_name
"Doe"
end
end
#Address model
class Address < ActiveRecord::Base
belongs_to :user
def self.full_name
parent.first_name + " " + parent.last_name
#returns full name of parent "John Doe"
end
end
我希望能夠在Rails的控制檯上運行這一點,並使其返回「李四」 ......但沒有運氣。有什麼建議麼?
@user = User.first
@user.addresses.full_name
對,我知道我可以在用戶模型本身中定義full_name。我想要做的是弄清楚如何從一個孩子內部訪問父方法。 – Chanpory 2010-11-09 01:41:50
我將問題簡化爲用戶/地址模式,以便於進行響應。我真正的問題涉及用戶模型和活動模型。 Activity模型由外部soap資源支持。我試圖做一個方法,我可以通過訪問user.user_id中的user_id來調用user.activities.refresh來獲取SOAP資源。我希望能夠做到這一點,如果活動數組是空的。 – Chanpory 2010-11-09 01:46:55
如果你想從孩子內部訪問父方法,你已經知道父方法,所以只需調用父方法。我很明顯困惑,並沒有得到你想要的東西:) – s84 2010-11-09 02:00:01