ActiveRecord- Inner Join两个SQL表+ Where子句

时间:2015-12-03 03:16:20

标签: mysql ruby-on-rails ruby activerecord

我在MySQL中有两个表,我想使用内部联接和基于表单输入的多个Where子句来调用SQL查询。我知道您可以通过ActiveRecord :: Base.connection执行原始SQL查询,但我想学习如何使用ActiveRecord对象。两个MySQL表的模式如下:

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脚本:

Select Inventory.* from Inventory
INNER JOIN Options
ON Inventory.VIN = Options.VIN
WHERE Inventory.Make = "Toyota"
AND Options.Leather = "Yes";

我在ActiveRecord中的Ruby类是这样的:

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

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

同样,我知道我可以将查询作为脚本输入,但我想通过Ruby最佳实践来学习如何做到这一点

1 个答案:

答案 0 :(得分:1)

您可以改为:

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

在我看来,我要说你必须将表格改为inventoriesoptions作为模型InventoryOption所以你不需要在每个模型中使用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

我希望这对你有所帮助。