Smart Relationships
Structure
Migrating
Relationships when the foreign key is accessible
# Model
class Forest::Product
include ForestLiana::Collection
collection :Product
has_many :buyers, type: ['String'], reference: 'Customer.id'
end
# routes.rb
namespace :forest do
get '/Product/:product_id/buyers' => 'orders#buyers'
end
mount ForestLiana::Engine => '/forest'
# Controller
class Forest::ProductsController < ForestLiana::ApplicationController
def buyers
limit = params['page']['size'].to_i
offset = (params['page']['number'].to_i - 1) * limit
product = Product.find(params['product_id'])
customers = Customer.where(order_id: product.orders.ids)
render json: serialize_models(customers.limit(limit).offset(offset), meta: {count: customers.count})
end
endRelationships when you need complex logic to get a foreign key
Last updated