Nic*_*ett 6 activerecord ruby-on-rails ruby-on-rails-4
假设我有这种关系
车型/ person.rb
class Person
belongs_to :group
end
Run Code Online (Sandbox Code Playgroud)
车型/ group.rb
class Group
has_many :people
end
Run Code Online (Sandbox Code Playgroud)
现在我创建一个人并分配一个新组
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.
Run Code Online (Sandbox Code Playgroud)
无论如何在搜索中包含未保存的记录?
我想要这样做的原因是我需要为一个组创建很多人,并且需要在中间执行where()查询以查看我是否已经添加了具有该名称的人.我希望在实例化所有人之后调用group.save,因为它在一个事务中执行,而不是每个人的单个事务,这个事情要慢得多.
Siv*_*iva 11
不将记录保存到数据库呈现where
方法无用.我能看到的唯一可能的解决方案就是Array
操纵.
你可以select
在这里利用ruby的数组方法
group.persons.new(name: 'John')
group.persons.new(name: 'Lucy')
group.persons.select{|x| x['name']=='Lucy'} # will return the record
Run Code Online (Sandbox Code Playgroud)