Rails Rabl gem: query child based on parent id

134 views Asked by At

The rails method:

def index
 user = Users.find(params[:user_id])
 @countries = user.countries
 @cities = user.cities
end

Country model has_many :cities

City model belongs_to :country

User has access to certain countries and certain cities

The corresponding json.rabl file:

object false
child @countries do 
 child @cities.where(country_name: country.name) do
  attributes :name, :coordinates
 end
end

My question is about child @cities.where(country_name: country.name)

My goal is to filter the @cities to only include the cities for the current parent country.

Is this possible in rabl?

1

There are 1 answers

0
Derek Hopper On

Instead of using an instance variable for @cities, you can use an association on your Country model.

The one question I would have, is this the index method for the User?

Something like this may work:

object @user
child :countries do
  child :cities do
    attributes :name, :coordinates
  end
end