相关疑难解决方法(0)

Rails - 仅查找存在has_many关联记录的记录

我有一个has_many与另一个模型有关系的模型,如下所示:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end
Run Code Online (Sandbox Code Playgroud)

由于有些父母可能没有孩子,我想做一个只返回有孩子的父母的查询.我怎么会这样做?

由于我在Rails 3上执行此操作,如果此查询不使用where.not.语法将会有所帮助.

postgresql activerecord ruby-on-rails ruby-on-rails-3

9
推荐指数
2
解决办法
3130
查看次数

查找与关联模型(表)至少具有一个关联的所有记录

假设我有这个:

class Tree < ActiveRecord::Base
  has_many :fruits
  has_many :flowers
end

class Fruit < ActiveRecord::Base
  belongs_to :tree
end

class Flower < ActiveRecord::Base
  belongs_to :tree
end
Run Code Online (Sandbox Code Playgroud)

如何进行有效的查询来获取Tree至少具有一个FlowerFruit实例或两者的所有实例?这个想法不是得到那些根本Tree没有的东西。FlowerFruit

model ruby-on-rails rails-activerecord

1
推荐指数
1
解决办法
2153
查看次数