has_and_belongs_to_many关系的Rails路由 [英] Rails routing for has_and_belongs_to_many relationship
问题描述
我正在为运动队开发Rails 4 API,那里有很多球员和球队,但是我在Rails路由和has_many
关系方面有些挣扎.我的球员和球队之间的关系如下:
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
我希望能够将一个现有的球员添加到一个团队中,但是我不确定如何更改我的routes.rb
文件.当前,它看起来像:
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
允许对玩家和团队模型进行CRUD操作.我当时想,要在现有团队中增加一名球员,我的路线将需要像这样:
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/
但是我不确定如何在routes.rb
中声明该路由.因此,有几个问题:
but I'm unsure of how to declare that route in routes.rb
. So, a couple of questions:
- 从REST风格的角度来看,这种路线对人们有意义吗?如果是这样,我将如何在
routes.rb
中声明这条路线
- 将队员添加到团队中应该是PATCH还是POST方法?
- 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,
塞恩
推荐答案
您可以这样声明此路由:
You can declare this route like this:
resources :teams, only: [:show, :create, :update, :destroy, :index] do
put 'add_player', on: :member
end
它将路线映射到TeamsController
中的add_player
操作.
It will map the route to the add_player
action in your TeamsController
.
从REST风格的角度来看,我还是建议您在players#update
动作中进行此操作,因为您基本上是在更改玩家记录.
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.
这篇关于has_and_belongs_to_many关系的Rails路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!