ruby - How to get data from other tables using Sequel -
i use sequel
, have following 2 models in sinatra app
# foo.rb require 'sequel' module notes module models class foo < sequel::model plugin :json_serializer, naked: true plugin :validation_helpers one_to_many :bars def validate super validates_presence [:foo_name], message: "can't empty" end end end end # bar.rb require 'sequel' module notes module models class bar < sequel::model plugin :json_serializer, naked: true plugin :validation_helpers many_to_one :foo def validate super validates_presence [:bar_name], message: "can't empty" end end end end
there foo_id
foreign key in bar table.
i have api route can bars or specific bar if parameter passed in, looks like:
app.get '/api/bars' require_session bar_name = params[:bar_name] bar_model = models::bar if bar_name.nil? bar_model.all.to_json else bar_model.where(sequel.ilike(:bar_name, '%' + bar_name + '%')) .all .to_json end end
what i'd haven't figured out yet how can @ least foo_name
foo table in result well, retrieved based on foo_id
that's in bar table?
even more, if there longer association, there's foreign key, example baz_id
, in foo table that's linked baz table, , in same api, want info foo , baz tables based on foreign key association in respective tables.
hope makes sense , appreciated.
you can use :include
option of sequel's to_json method this. can specify in model when set json_serializer options, can override defaults when call to_json on instance.
so, on individual instance of bar, do:
bar.first.to_json(include: {foo: {only: :foo_name}})
if want full list, in example, want call on class. note if call on array won't work, must call on dataset before converting array.
# models bar.to_json(include: {foo: {only: :foo_name}}) # subset of models bar.where(sequel.ilike(:bar_name, '%' + bar_name + '%')) .to_json(include: {foo: {only: :foo_name}})
Comments
Post a Comment