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

ruby-on-rails – Rails“where”子句用于关联

发布时间:2020-12-17 03:39:57 所属栏目:百科 来源:网络整理
导读:这似乎是一个简单的问题,但这对我来说有点困惑: class Parent has_many children ...endclass Child belongs_to parentendp = Parent.find(111)c = Child.all.where(parent: p) 为什么不起作用,我该怎么做: c = Child.all.where(parent_id: p.id) 谢谢! *
这似乎是一个简单的问题,但这对我来说有点困惑:

class Parent
  has_many children
  ...
end

class Child
  belongs_to parent
end

p = Parent.find(111)
c = Child.all.where(parent: p)

为什么不起作用,我该怎么做:

c = Child.all.where(parent_id: p.id)

谢谢!

*附录*

更复杂的情况是我根据更复杂的逻辑创建一个Relation,例如

c = Child.where(age: 32,city: "boston")
c.where(parent: p) # wouldn't work

*附录#2 *

等等我需要有多对多来说明这一点:

class Teacher
   has_many :students,through: ClassRoom
   has_many :classes
end

class ClassRoom
  belongs_to :teacher
  belongs_to :child
end

class Child 
  has_many :classes
  has_many :teachers,through: ClassRoom
end
t = Teacher.first
c = Child.where(age: 5,city: "boston")

c.where(teacher: t) # wouldn't work
c.where(teacher_id: t.id) # would work but is a little ugly

*附录3 *

谢谢你提供这些很棒的信息!从上面的例子开始,最后一行是否有更好(或’正确’)的方法?

c.where(teacher_id: t.id) # would work but is a little ugly

解决方法

你可以做:

p = Parent.find(111)
all_children = p.children

关键父级不起作用,因为它使用它作为列名称.

附录:

所以对于这个用例你应该使用:

class ClassRoom < ActiveRecord::Base
  belongs_to :teacher
  belongs_to :child
end

class Teacher < ActiveRecord::Base
  has_many :children,through: ClassRoom
  has_many :class_rooms
end

class Child < ActiveRecord::Base
  has_many :class_rooms
  has_many :teachers,through: ClassRoom
end

t = Teacher.first
teachers_children_from_boston_and_32 = t.children.where(age: 32,city: "boston")

首先,你不能使用Class,因为它已经是一个对象.
下一个问题是您将孩子重命名为学生,您可以这样做,但需要在has_many调用上做一些其他选项.

在这里查看连接表:http://guides.rubyonrails.org/active_record_querying.html#joining-tables

和Assoications在这里(您的用例完美匹配此示例):
http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

还记得rails 3所有where子句只是critera.
Critera用于查找您的匹配项,可以一起添加以缩小搜索结果范围. IE

where_clause_one = Teacher.where(age: 50)
where_clause_two = Teacher.where(city: "San Francisco")
merged_where_clauses = where_clause_one.merge(where_clause_two)
merged_where_clauses.each do |teacher|
  # teachers that are both 50 and from san francisco
  ...
end

(编辑:李大同)

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

    推荐文章
      热点阅读