Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Using .where() on dirty (unsaved) relations

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.

like image 946
Nick Barrett Avatar asked Mar 03 '14 05:03

Nick Barrett


1 Answers

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

like image 120
Siva Avatar answered Oct 17 '22 06:10

Siva