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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With