2013-09-10 74 views
1

时返回nil我与同时通过嵌套形式建成了的has_many关系的模型:CollectionProxy创建新对象

class User < ActiveRecord::Base 
    has_many :properties 
    accepts_nested_attributes_for :properties, allow_destroy: true 

    def billing_address 
    debugger 
    properties.find_by(billing_address: true) 
    end 
end 

总体而言,关系和嵌套形式的作品。但是,如果在创建过程中调用方法billing_address,则即使存在billing_address设置为true的嵌套属性,它也会返回nil。我在调试器中对此进行了尝试,似乎在创建过程中调用properties.find_byproperties.where总是会导致nil,即使这些参数与实际对象匹配。

当我键入properties到调试,我得到的结果是这样,这清楚地表明,与billing_address属性设置为true:

#<ActiveRecord::Associations::CollectionProxy [#<User::Property id: nil, address: "1111 E 1st", city: "Austin", state: "TX", zip_code: "11111", phone_number: "11111111111", user_id: nil, primary: true, billing_address: true, created_at: nil, updated_at: nil>]> 

那么,为什么不能用我等查询发现,作为properties.find_by(billing_address: true)?是否有另一种获取这些数据的方法?

回答

0

find_bywhere搜索数据库(通过SQL查询)并且在您检查时,记录尚未保存,因此无法在其中找到记录。我知道无法“查找”代理服务器,但如果您提供有关您尝试访问它们的上下文的更多信息,我可能会有一些想法。

+0

我在验证呼叫期间访问它们。它在模型层,所以我没有直接访问参数。任何其他细节可能有帮助? – nullnullnull

+0

分享正在进行呼叫的验证码可能会有所帮助。 –

+0

这是引发错误的行:'BraintreeRails :: Customer.create!(first_name:first_name,last_name:last_name,email:email,phone:billing:address_address.phone_number)' – nullnullnull