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:
routes.rb
Thanks for any help offered,
Sean
You can declare this route like this:
resources :teams, only: [:show, :create, :update, :destroy, :index] do
put 'add_player', on: :member
end
It will map the route to the add_player
action in your TeamsController
.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments