Sql 如何跨关联创建单个查询
我有一个Sql 如何跨关联创建单个查询,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我有一个用户模型,它有一个配置文件,还有一个目标。profile有一个hstore类型的隐私字段,在该字段中可以有一个散列,表示可以公开显示goal,如果可以显示goal,则散列看起来像{'show\u goals'=>'1'}。我想要一个可以公开显示的所有目标的列表。我最初的尝试是 def list_public profiles = Profile.includes(:user).where("privacy @> hstore('show_goals','1')")
用户
模型,它有一个配置文件
,还有一个目标
。profile
有一个hstore类型的隐私字段,在该字段中可以有一个散列,表示可以公开显示goal
,如果可以显示goal
,则散列看起来像{'show\u goals'=>'1'}。我想要一个可以公开显示的所有目标的列表。我最初的尝试是
def list_public
profiles = Profile.includes(:user).where("privacy @> hstore('show_goals','1')")
goals = []
profiles.each do |p|
goals << p.user.goals.first
end
goals
end
end
def list\u public
profiles=Profile.includes(:user).where(“privacy@>hstore('show_goals','1'))
目标=[]
剖面图。每个do | p|
目标最简单的方法是在查询中加载goals
:
profiles = Profile.includes(:user, user: :goals).where("privacy @> hstore('show_goals','1')")
这将产生一个额外的查询,获取所有目标。然后仍然可以按原样使用剩余的代码,p.user.goals.first
将不会生成额外的数据库查询