6

Suppose I have this relationship

models/person.rb

class Person
  belongs_to :group
end

models/group.rb

class Group
  has_many :people
end

Now I create a person and assign a new group

group = Group.create(name: 'Group A')
group.person.new(name: 'John')
group.person.new(name: 'Lucy')
# Now if I call group.person.where(name: 'Lucy') 
# here it will return an empty result, 
# because it has not been persisted to the database.

Is there anyway to include the unsaved records in the search?

My reason for wanting to do this is I need to create a lot of people for a group, and need to perform a where() query in the middle to see if I have already added someone with that name. I would rather just call group.save after instantiating all the people as it executes in one transaction rather than an individual transaction for each person which is much slower.

Nick Barrett
  • 1,051
  • 2
  • 11
  • 28

1 Answers1

11

Not saving the records to database renders where method useless. Only possible solution I can see here is Array manipulation.

You can take advantage of ruby's array select method here

group.persons.new(name: 'John')
group.persons.new(name: 'Lucy')

group.persons.select{|x| x['name']=='Lucy'} # will return the record

Refer this question and documentation

Community
  • 1
  • 1
Siva
  • 7,780
  • 6
  • 47
  • 54
  • Update the select block to use == – steakchaser Mar 03 '14 at 06:11
  • 1
    @shiva : But `=` is wrong. It changes the name of the first record and returns the record after that, because the name is not `nil`. Must be `==` – spickermann Mar 03 '14 at 06:20
  • `=` sets the value of x['name']. `select` wants a conditional. Per the docs `Invokes the block passing in successive elements from self, returning an array containing those elements for which the block returns a true value` – steakchaser Mar 03 '14 at 06:20
  • Cool. Nick will need to combine this checking of the new records with checking of existing records. I would probably just issue a query for the existing records: `Persons.where(:name, "Lucy").count == 0` – steakchaser Mar 03 '14 at 06:28