2016-11-02 6 views
0

Documentというモデルと、DocumentPropertyというhas_manyのモデルがあります。複数のプロパティを持つモデルを検索する(プロパティはキー=>値テーブルにあります)

DocumentPropertyは、id,document_id,keyおよびvalueの列を有する。

私は2つ以上のキー=>値のペアを持つドキュメントを検索するクエリを考え出しています。例えば、サイズ= A4 ページ= 2のドキュメントですが、すべてのSQLを自分で書くことなく(現在はActiveRecord :: Relationを使用して)これを行う方法を見つける。

例表データ:私の検索では

| document_id | key | value | 
+-------------+--------+---------+ 
| 1   | size | A4  | 
| 1   | pages | 2  | 
| 2   | size | A4  | 
| 2   | pages | 3  | 
| 3   | size | A4  | 
| 3   | pages | 2  | 
| 3   | author | Brandon | 

、文書1と3が返されます。

Railsはこれをサポートしていますか?

+0

解決していますか? –

答えて

0

うん、ActiveRecordのは、このようなクエリをサポートしています。

Document.joins(:document_properties) 
     .where("document_properties.key = 'size' AND document_properties.value = 'A4' OR document_properties.key = 'pages' AND document_properties.value = 2") 
     .group('documents.id') 
+0

私のポストをもっと見ると、document_propertiesには4列しかありません。私の例では、1行にA4のサイズと値のキーがあります。サイズは列ではありません。 –

+0

@BrandonWamboldt答えを編集しました –

0

私はレールでモデルを構築しています。これを試してください。計算されたドキュメントIDは、まず

2.2.3 :002 > document_ids = DocumentProperty.where(key: 'size', value: 'A4').pluck('document_id') & DocumentProperty.where(key: 'pages', value: '2').pluck('document_id') 
    (0.3ms) SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'size' AND `document_properties`.`value` = 'A4' 
    (0.3ms) SELECT `document_properties`.`document_id` FROM `document_properties` WHERE `document_properties`.`key` = 'pages' AND `document_properties`.`value` = '2' 
=> [1, 3] 
2.2.3 :003 > Document.where(id: document_ids) 
    Document Load (1.1ms) SELECT `documents`.* FROM `documents` WHERE `documents`.`id` IN (1, 3) 
=> #<ActiveRecord::Relation [#<Document id: 1, name: "first", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">, #<Document id: 3, name: "three", created_at: "2016-11-02 14:07:38", updated_at: "2016-11-02 14:07:38">]> 
2.2.3 :004 > 
関連する問題