我正在那里开发 Ruby on Rails 应用程序, AnalyticsPage 具有以下关系。 与用户的多对多关系。 上面的查询没有给出用户的名字和姓氏。另一点是,当我运行 SQL 查询时,它是在 mysql admin 中运行的。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
如何使用联接查询Rails 5中的关联模型? 在查看文档和这个问题之后,我尝试过的是DoctorLocation.joins(:location).where(:location => {:confidence => 2})
。 我究竟做错了什么? 我的查询未返回任何结果。
pry(main)> DoctorLocation.joins(:locations).where(:locations => {:confidence => 2})
=> #<DoctorLocation::ActiveRecord_Relation:0x3ff735a09d8c>
class DoctorLocation
belongs_to :location
end
class Location
has_many :doctor_locations, dependent: :destroy
end
移民
create_table :doctor_locations do |t|
t.integer :doctor_profile_id
t.integer :location_id
t.text :uuid
t.timestamps null: false
end
create_table :locations do |t|
t.string :address
t.integer :ordinal, :default => 1
t.integer :doctor_profile_id
t.text :uuid
t.timestamps
end
add_column :locations, :confidence, :integer
您实际上有正确的查询。 而是您的测试方法已损坏。
class DoctorLocation < ApplicationRecord
belongs_to :location
def self.with_confidence(c)
DoctorLocation.joins(:location).where(locations: { confidence: c })
end
end
通过的规范确认它可以按预期工作:
require 'rails_helper'
RSpec.describe DoctorLocation, type: :model do
after(:each) { DoctorLocation.destroy_all }
it "includes locations with the correct confidence" do
dl = DoctorLocation.create!(location: Location.create!(confidence: 2))
DoctorLocation.create!(location: Location.create!(confidence: 1))
expect(DoctorLocation.with_confidence(2)).to include dl
expect(DoctorLocation.with_confidence(2).count).to eq 1
end
it "does not include rows without a match in the join table" do
dl = DoctorLocation.create!(location: Location.create!(confidence: 1))
expect(DoctorLocation.with_confidence(2)).to_not include dl
end
end
在joins
及其where
(散列参数)中,您需要声明关联名称( location
),而不是表名称( locations
):
DoctorLocation.joins(:location).where(location: { confidence: 2 })
这通常是造成混乱的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.