diff --git a/app/controllers/api/v1/parks_controller.rb b/app/controllers/api/v1/parks_controller.rb index 193b296..9340128 100644 --- a/app/controllers/api/v1/parks_controller.rb +++ b/app/controllers/api/v1/parks_controller.rb @@ -5,7 +5,7 @@ module Api::V1 def index parks = Park.all if params[:state].present? - parks = parks.where("states like '%' || ? || '%'", params[:state]) + parks = parks.joins(:states).where(parks_by_states: { state: params[:state] }) end render json: { total: parks.count, diff --git a/app/models/park.rb b/app/models/park.rb index df67b8b..1f5df8e 100644 --- a/app/models/park.rb +++ b/app/models/park.rb @@ -1,4 +1,7 @@ class Park < ApplicationRecord has_many :alerts, foreign_key: :park_code, primary_key: :code, inverse_of: :park, dependent: :destroy + has_many :states, class_name: "ParksByState", + foreign_key: :park_code, primary_key: :code, + inverse_of: :parks, dependent: :destroy end diff --git a/app/models/parks_by_state.rb b/app/models/parks_by_state.rb index 8dc4e37..a73f9e3 100644 --- a/app/models/parks_by_state.rb +++ b/app/models/parks_by_state.rb @@ -1,2 +1,4 @@ class ParksByState < ApplicationRecord + has_many :parks, foreign_key: :park_code, primary_key: :code, + inverse_of: :states end diff --git a/spec/fixtures/parks_by_states.yml b/spec/fixtures/parks_by_states.yml new file mode 100644 index 0000000..d3cb43d --- /dev/null +++ b/spec/fixtures/parks_by_states.yml @@ -0,0 +1,9 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + park_code: crla + state: OR + +two: + park_code: olym + state: WA