加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ActiveRecord在脏(未保存)关系上使用.where()

发布时间:2020-12-17 03:48:51 所属栏目:百科 来源:网络整理
导读:假设我有这种关系 车型/ person.rb class Person belongs_to :groupend 车型/ group.rb class Group has_many :peopleend 现在我创建一个人并分配一个新组 group = Group.create(name: 'Group A')group.person.new(name: 'John')group.person.new(name: 'Luc
假设我有这种关系

车型/ person.rb

class Person
  belongs_to :group
end

车型/ group.rb

class Group
  has_many :people
end

现在我创建一个人并分配一个新组

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.

无论如何在搜索中包含未保存的记录?

我想要这样做的原因是我需要为一个组创建很多人,并且需要在中间执行where()查询以查看我是否已经添加了具有该名称的人.我希望在实例化所有人之后调用group.save,因为它在一个事务中执行,而不是每个人的单个事务,这个事情要慢得多.

解决方法

不将记录保存到方法无用的数据库渲染.我可以看到的唯一可能的解决方案是数组操作.

你可以在这里利用ruby的数组选择方法

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

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

参见this question和documentation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读