如何使用联接查询Rails 5中的关联模型?我尝试过的是查看documentation和此question之后的public class Launcher extends Application {
public static PSurfaceFX surface;
@Override
public void start(Stage primaryStage) throws Exception {
Canvas canvas = (Canvas) surface.getNative(); // boilerplate
GraphicsContext graphicsContext = canvas.getGraphicsContext2D(); // boilerplate
surface.fx.context = graphicsContext; // boilerplate
primaryStage.setTitle("FXML/Processing");
VBox root = FXMLLoader.load(new File("c:/Users/Mike/desktop/test.fxml").toURI().toURL());
SplitPane pane = (SplitPane) root.getChildren().get(1); // Manually get the item I want to add canvas to
AnchorPane pane2 = (AnchorPane) pane.getItems().get(0); // Manually get the item I want to add canvas to
pane2.getChildren().add(canvas); // Manually get the item I want to add canvas to
canvas.widthProperty().bind(pane2.widthProperty());
canvas.heightProperty().bind(pane2.heightProperty());
Scene scene = new Scene(root, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
surface.stage = primaryStage; // boilerplate
}
}
。我究竟做错了什么?我的查询没有返回任何结果。
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
答案 0 :(得分:1)
您实际上有正确的查询。而是您的测试方法已损坏。
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
答案 1 :(得分:0)
在joins
和where
(散列参数)中,您需要声明关联名称(location
),而不是表名称(locations
):
DoctorLocation.joins(:location).where(location: { confidence: 2 })
通常是造成混乱的原因。