Using Pluck with a new record and a has_many relationship giving unexpected result. #8102

Closed
remomueller opened this Issue Nov 2, 2012 · 2 comments

Comments

Projects
None yet
3 participants
Contributor

remomueller commented Nov 2, 2012

Not sure if this is intended or not, but I ran into the following result when working with pluck and a newly instantiated record. (Tested in Rails 3.2.8 and 3.2.9.rc2 against mysql2 0.3.11)

Setup

# person.rb
has_many :pets
# pet.rb
belongs_to :person

Using pluck to get associated ids with a new record.

@person = Person.new
# => #<Person id: nil, created_at: nil, updated_at: nil> 
@person.pets.pluck(:id)
# Expected
# => []
# Actual Result
# SELECT id FROM `pets` WHERE `pets`.`person_id` IS NULL
# => [1,2,3,4,5,6,...] ids of all pets that have person_id set to nil

I expected to see the empty array [] since leaving .pluck(:id) off would return an empty ActiveRecord relationship

@person = Person.new
@person.pets
# => []

While I can check explicitly for new_record? and solve my problem that way (as it works correctly with saved records), it seems that the expected result doesn't match.

I understand what pluck is doing in building the relationship and why it's retrieving associated records, however I'd like to know if anyone has further insight on whether pluck is intended to work with new records and relationships like this?

Thanks!

Although not exactly the same problem, I think this is close enough to #5215 that it can be considered duplicate.

@remomueller Please check out the discussion over there :)

Contributor

remomueller commented Nov 2, 2012

Thanks @colszowka! This is indeed the same issue, resolving that one would resolve this issue too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment