ruby-on-rails - Rails "where"关联子句

标签 ruby-on-rails activerecord

这似乎是一个简单的问题,但对我来说却是一个小难题:

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)

附录

一个更复杂的案例让我基于更复杂的逻辑创建一个关系,例如
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

最佳答案

.all将 ActiveRecord::Relation 对象转换为数组。数组不响应 where方法。你应该使用

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

在这种情况下你必须使用 _id 因为 where将直接将给定的哈希转换为 SQL。 SQL不知道什么parent是,它只知道什么parent_id是。话虽如此,最好的方法是
c = p.children

关于ruby-on-rails - Rails "where"关联子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244411/

相关文章:

ruby-on-rails - Ruby on Rails - 订单不适用于 distinct.pluck

ruby-on-rails - ActionController::InvalidAuthenticityToken 和域名

mysql - Rails 控制台未将数据写入数据库

ruby-on-rails - 如何使用 has_many :through and honor :conditions? 创建新记录

ruby-on-rails - 自动加载常量时检测到循环依赖(Rails 4、Ruby 2)

ruby-on-rails - rails 4 : Want to check if an object already exists when submitting a form and then update that record with additional info (many-to-many relationship)

ruby-on-rails - Rails 5 具有多个子查询的复杂查询

ruby-on-rails - 实例的 ActiveRecord 事务 block 和类有什么区别?

ruby-on-rails - 从 Active Record 范围内访问类方法?

mysql - 基于参数的 Rails 自定义查询