CollectionProxy returns nil when creating a new object
I have a model with a has_many relationship that's built through nested
forms:
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
Overall, the relationship and nested form works. However, if I call the
method billing_address during creation, then it returns nil, even if there
is a nested property with billing_address set to true. I experimented with
this in debugger, and it seems that calling properties.find_by or
properties.where during creation always results in nil, even if the
parameters match a real object.
When I type properties into debugger, I get results like this, which
clearly show that there is a property with billing_address set to 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>]>
So why can't I find it with a query such as
properties.find_by(billing_address: true)? Is there another approach to
getting at this data?
No comments:
Post a Comment