2015-12-03 93 views
0

我在MySQL中有兩個表格,我想根據表單的輸入使用內部聯接和多個Where子句調用SQL查詢。我知道你可以通過ActiveRecord :: Base.connection執行一個原始的SQL Query,但是我想學習如何使用ActiveRecord對象。對於兩個MySQL表的模式就像這樣:ActiveRecord-內部加入兩個SQL表格+ Where Where子句

Describe Options; 

'VIN','varchar(45)','NO','PRI',NULL,'' 
'LEATHER','varchar(45)','YES','',NULL,'' 
'4WD','varchar(45)','YES','',NULL,'' 
'FOGLIGHTS','varchar(45)','YES','',NULL,'' 
'DVD','varchar(45)','YES','',NULL,'' 
'SURROUND','varchar(45)','YES','',NULL,'' 

Describe Inventory; 
'VIN','varchar(30)','NO','PRI',NULL,'' 
'MAKE','varchar(30)','NO','',NULL,'' 
'MODEL','varchar(30)','NO','',NULL,'' 
'TYPE','varchar(50)','NO','',NULL,'' 

我想執行像這樣一個SQL腳本:

​​

我的Ruby類在ActiveRecord的是像這樣:

class Option < ActiveRecord::Base 
    self.table_name = "Options" 
end 

class Inventory < ActiveRecord::Base 
    self.table_name = "INVENTORY" 
end 

Aga在,我知道我可以只輸入查詢作爲一個劇本,但我想了解如何做到這一點通過Ruby的最佳實踐

回答

1

您可以更改成這樣:

Inventory.joins("INNER JOIN Options ON Inventory.VIN = Options.VIN") 
     .where("Inventory.Make = ? AND Options.Leather = ?", "Toyota", "YES") 

在我看來,我想說你必須改變你的表inventoriesoptionsInventoryOption,所以你不需要在每個模型中使用set_table_name。這是關於rails慣例風格的代碼。然後你可以看到這樣的模型。

class Inventory < ActiveRecord::Base 
    has_many :options, foreign_key: "VIN" 
end 

class Option < ActiveRecord::Base 
    belongs_to :inventory, foreign_key: "VIN" 
end 

我希望這對你有所幫助。