2012-11-07 44 views
3

这里是我的组织...问题与联创

Account has_many :credits 
Credit belongs_to :account 

而且我试图运行:account.credits.current

所以,在这种情况下,我已经有一个Account对象,那么我想访问Credit模型中的current方法。

这里是一个方法...

def self.current 
    # Find current credit line 
    current = self.where(:for_date => Time.now.strftime("%Y-%m-01")).first 

    # If we couldn't find a credit line for this month, create one 
    current = Credit.create(:account_id => self.account.id, :for_date => Time.now.strftime("%Y-%m-01")) if current.blank? 

    # Return the object 
    current 
end 

的问题是,第二行...这应该创建一个新的信贷项,如果它不能找到一个的一个。具体来说,我无法设置应该关联的帐户。我刚刚得到一个undefined method 'account'错误。

+0

可能是一个长镜头,但你有没有尝试过只是'account.id'? –

+0

@ Zephph:是的......我得到了一个未定义的局部变量或方法'账户'。 – Shpigford

+0

免责声明:这些自我vs平均定义让我感动,我仍然在学习,但如果您将方法从自我中移除,那么该怎么办?本地正常工作:“def current account.id end”Credit.current返回关联账户的ID。 –

回答

1

创建通过协会来代替,并离开了account_id,因为它会自动链接:

current = self.create(:for_date => Time.now.strftime("%Y-%m-01")) if current.blank? 

注:self.create代替Credit.create

+0

不起作用。如果没有'self'我就不能访问'current'方法。如果我这样做,那么我会得到'undefined method'current''。 – Shpigford

+0

虽然我认为问题是关联。你尝试过'Account.find(1).credits.current'吗? – Shpigford

+0

对不起,我马上更新我的答案。我没有完全理解你是如何尝试使用这个模型的。 –

0

您试图访问类方法中的实例属性,这是不可能的。

如果你有这样的:

class Credit 
    def self.current 
     self.account 
    end 
end 

这是一样的:Credit.account,这是我敢肯定,你明白,是行不通的。

现在,你的方法,如果你想让它在多个协会加载current必须是一个类的方法:即:

随着def self.current可以调用account.credits.current

随着def current你可以打电话account.credits[0].currentaccount.credits.where(...).current

我希望这是有道理的。现在,作为该怎么办吧...

我的建议是做一个current范围,就像这样:

class Credit 
    scope :current, lambda { where(:for_date => Time.now.strftime("%Y-%m-01")).first } 
    ... 
end 

然后你就可以在任何地方使用这个范围,有一个实例(或为零)在它的结尾。

account.credits.create(...) unless accounts.credit.current 

如果你想使一个方便的方法,我会再做:

级信用 高清self.current_or_new self.current || self.create(:for_date => Time.now.strftime(“%Y-%m-01”)) end end

这应该按照您的打算。如果它通过一个关联进行调用,即:

account.credits.current_or_new 

然后,account_id将通过关联放置在您的轨道上。

+0

答案是以上^^通过关联创建。 –