Ale*_*pov 7 activerecord ruby-on-rails active-record-query
如果我有一个模型Person,has_many Vehicles每个模型都Vehicle可以是类型,car或者motorcycle我如何查询所有拥有汽车的人和所有拥有摩托车的人?
我不认为这些是正确的:
Person.joins(:vehicles).where(vehicle_type: 'auto')
Person.joins(:vehicles).where(vehicle_type: 'motorcycle')
Run Code Online (Sandbox Code Playgroud)
MrY*_*iji 15
您可以执行以下操作:
Person.includes(:vehicles).where(vehicles: { type: 'auto' })
Person.includes(:vehicles).where(vehicles: { type: 'motorcycle' })
Run Code Online (Sandbox Code Playgroud)
小心.joins和.includes:
# consider these models
Post # table name is posts
belongs_to :user
#^^
User # table name is users
has_many :posts
#^
# the `includes/joins` methods use the relation name defined in the model:
User.includes(:posts).where(posts: { title: 'Bobby Table' })
#^ ^
# but the `where` uses the exact table name:
Post.includes(:user).where(users: { name: 'Bobby' })
#^^^ ^
Run Code Online (Sandbox Code Playgroud)
一个棘手的问题:
Post
belongs_to :author, class_name: 'User'
User # table named users
has_many :posts
Post.includes(:author).where(users: { name: 'John' })
# because table is named users
Run Code Online (Sandbox Code Playgroud)
类似的问题:
| 归档时间: |
|
| 查看次数: |
2310 次 |
| 最近记录: |