I have an API that have three models: Website, Message, Condition.
- Website has many Messages
- Message has many Conditions
- Condition model is STI, and has multiple types
Here is an example of a message
#<Message:0x00007fb4e82fa0e0> {
:body => nil,
:created_at => Wed, 08 Jul 2020 20:06:53 UTC +00:00,
:id => 1,
:website_id => 1,
:subtitle => nil,
:title => "msg 1",
:updated_at => Wed, 08 Jul 2020 20:06:53 UTC +00:00
}
and it's conditions
[
[0] #<Condition::StorefrontPage:0x00007fb4e1b24420> {
"condition_active" => true,
"condition_attributes" => {
"account" => false,
"blogs" => false,
"cart" => false,
"collections" => false,
"everywhere" => false,
"homepage" => false,
"pages" => true,
"products" => false
},
"created_at" => Wed, 08 Jul 2020 20:06:53 UTC +00:00,
"id" => 1,
"message_id" => 1,
"title" => nil,
"type" => "Condition::PageDetails",
"updated_at" => Wed, 08 Jul 2020 20:06:53 UTC +00:00
},
[1] #<Condition::Geolocation:0x00007fb4ec137dd0> {
"condition_active" => true,
"condition_attributes" => {
"country_code" => "US"
},
"created_at" => Wed, 08 Jul 2020 20:06:53 UTC +00:00,
"description" => nil,
"id" => 2,
"message_id" => 1,
"title" => nil,
"type" => "Condition::Geolocation",
"updated_at" => Wed, 08 Jul 2020 20:06:53 UTC +00:00
}
]
The API receives params in a GET request from a website page, example:
{
website_id: "1",
page_attributes: {
page_type: "page",
page_handle: "contact-us"
},
geolocation_attributes: {
country_code: "CA",
region_code: "BC",
city: "victoria"
}
}
Those params describe the page and where the request is coming from.
Message conditions might match any or none of the incoming attributes.
I'm trying to figure out a way to find a message by all of it's conditions based on the incoming request params without having to chain lots of where statement.
One of the challenges also is that the condition attributes are stored in jsonb column and I'm not able to add it to this:
# How can I merge this
# DisplayCondition.where("condition_attributes->>'country_code' = ?", "CA")
# Into...
Message.joins(:conditions).where(:conditions => {:type => "Condition::Geolocation"})
TIA