class Account has_many :metadata class Keys has_many :metadata class Metadatum belongs_to :key belongs_ to :account In Metadatum object I keep additional information about Account, for exapmle 'age'.
In Key object I keep information about type of Metadatum.
Metadatum table:
- id
- key_id
- account_id
- value
Key table:
- name
- data_type
I want to search accounts by multiple metadata. For example
- Metadatum with value = '18' that belongs to Key with name = 'age'
- Metadatum with value = 'John' that belongs to Key with name = 'first_name'
My query is:
accounts.joins(metadata: :key).where("keys.name = ? AND metadata.value = ?", params[:key], params[:value]).where("keys.name = ? AND metadata.value = ?", params[:key1], params[:value1]) It is wrong because in my opinion it looks for an Account that has Metadatum with both key_ids and values. No such Metadatum exists - each has only one key_id and value.
What would be the right query?