In my API I want an endpoint to provide a subject account's ID and have it return other account records associated with the subject. My models are as follows:
This is my main account model. Both subjects and associates are of type account:
class TabAccount < ApplicationRecord
has_many :subjects, through: :subject_tab_account_relationships, source: :subject
has_many :subject_tab_account_relationships, foreign_key: :id_associate, class_name: "TabAccount"
has_many :associates, through: :associate_tab_account_relationships, source: :associate
has_many :associate_tab_account_relationships, foreign_key: :id_subject, class_name: "TabAccount"
end
This is my account relationship model. This provides the many-to-many self-join relationships between subjects and associates:
class TabAccountRelation < ApplicationRecord
belongs_to :ref_relationship_type
belongs_to :subject, foreign_key: "id_subject", class_name: "TabAccount"
belongs_to :associate, foreign_key: "id_associate", class_name: "TabAccount"
end
I know that works because I'm able to use the model inside my Rails code but I'm not entirely sure how to expose this relationship through an endpoint. I know in the routes map file you're supposed to add child resources to a parent resource, but I'm not sure what's the child in this case. This is what I have so far for my route mapping:
resources :tab_accounts do
resources :associates
end
And here's my account controller:
# GET /tab_accounts/:id_subject/associates
# GET /tab_accounts/:id_subject/associates.json
def index
if params[:id_subject]
_limit = if params[:limit].present? then params[:limit] else 100 end
@tab_accounts = TabAccount.find(params[:id_subject]).associates.limit(_limit)
else
@tab_accounts = TabAccount.offset(params[:offset]).limit(_limit)
end
end
And here's my output to stderr:
Started GET "/tab_accounts/2646/associates.json?limit=5" for 127.0.0.1 at 2018-03-21 22:51:54 -0400
ActionController::RoutingError (uninitialized constant AssociatesController):
Has anyone ever exposed aliases/sources through endpoints before? How did you do it? Am I close to getting it right?
Instead of adding nested resources you can add additional routes to your existing resource. See http://guides.rubyonrails.org/routing.html#adding-more-restful-actions .
So instead of using this:
resources :tab_accounts do
resources :associates
end
you can switch to this:
resources :tab_accounts do
member do
get :associates
end
end
You would then add the corresponding associates
action to your existing Accounts controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.