I'm working on a rails 4 API for a sports team where I have players and teams and I'm struggling a little with rails routing and a has_many
relationship. My relationship between players and teams looks like:
class Team < ActiveRecord::Base
extend Searchable
validates :title, presence: true
has_and_belongs_to_many :players
end
class Player < ActiveRecord::Base
extend Searchable
validates :first_name, presence: true
validates :last_name, presence: true
has_and_belongs_to_many :teams
end
I'd like to be able to add an existing player to a team, but I'm unsure of how to change my routes.rb
file. Currently, it looks like:
Rails.application.routes.draw do
devise_for :users
namespace :api, defaults: { format: :json },
constraints: { subdomain: 'api' }, path: '/' do
scope module: :v1 do
resources :users, :only => [:show, :create, :update, :destroy]
resources :teams, :only => [:show, :create, :update, :destroy, :index]
resources :players, :only => [:show, :create, :update, :destroy, :index]
resources :sessions, :only => [:create, :destroy]
end
end
end
which allows for CRUD operations on players and teams models. I was thinking that for adding a player to an existing team, my route would need to look like:
/teams/:team_id/add_player/
but I'm unsure of how to declare that route in routes.rb
. So, a couple of questions:
- Does that route make sense to people from a REST-ful perspective? If so, how would I declare this route in
routes.rb
- Should it be a PATCH or a POST method for adding a player to a team?
Thanks for any help offered,
Sean
You'll need to use a nested resource:
This will route to your
players_controller
, passing the:team_id
param:You'd be able to couple this with the following view:
--
Trivia:
With HABTM, you get the
<<
&collection.delete
methods -- both allowing you to add and remove objects from a collection super simply.-
Yep.
In line with the resourceful routing structure, I'd say you could get away with a
POST
request to thecreate
action, but it could be done a number of ways!Update
Do this:
This will create the following routes:
This will allow you to use a
players
method in yourteams
controller:You can declare this route like this:
It will map the route to the
add_player
action in yourTeamsController
.From the REST-ful perspective i would suggest you to make this in the
players#update
action though, since you are basically changing the player record.