2013-10-07 44 views
0

我的Rails 4应用程序中的两个模型是 - Accommodation.rbAccount.rb - 每个住宿has_one帐户。从其他模型调用模型

在我Accommodation.rb我有这样的方法:

def my_method 
    self.field = "Something" 
    save! 
end 

,我打电话使用从AccommodationsController.rb方法:

accommodation.my_method 

,但我也需要能够调用一个方法在我Account.rb从我的Accommodation.rb模型,同时保持关联,以便如果我创建或更新帐户表中的记录,它将知道哪个住宿ID参考。对东西的线路:

Account.accommodation.my_other_method 

,但我知道这是行不通的,因为它是一个“刺在黑暗中”

注意我试图让我的逻辑在我的模型

+1

您可能只需为相关记录调用'@ accommodation.account'和'@ account.accommodation'。 –

回答

4

要引用关联的模型(例如为了调用它的方法),只需使用与模型名称匹配的自动生成的方法。

例如,如果住宿has_one帐户和accommodation是住宿对象,您可以拨打accommodation.account来引用关联的帐户。该参考可以有方法调用了它正常的:accommodation.account.my_account_instance_method(foo)

另外,如果你在住宿的方法定义的时候,你可以直接引用的方法:

class Accommodation 
    has_one :account 

    def do_something 
    account.my_account_instance_method 
    end 
end 

所有这一切都非常好记录在Rails associations basics guide中,我强烈建议您至少简要地浏览一下。

+0

非常有帮助 - 谢谢 – tommyd456

+0

是啊!那就对了。 –