routes in rails?

0

I have the models Player , Team and PlayerTeam ; PlayerTeam is the middle table that forms the many to many relationship between Player and Team .

player.rb:

class Player < ApplicationRecord   
  has_many :player_teams   
  has_many :teams , through: :player_teams

  before_save do
    self.numero_goals = 0
    self.reputation = 0
    self.plays_win = 0
    self.plays_lose = 0 
  end  
end

team.rb:

class Team < ApplicationRecord 
  has_many :player_teams, dependent: :destroy  
  has_many :players, through: :player_teams  
  has_many :team_battles, dependent: :destroy  
  has_many :battles, through: :team_battles 
end

player_team.rb:

class PlayerTeam < ApplicationRecord
  belongs_to :player
  belongs_to :team
end

The routes I currently have it like this:

resources :players do
  resources :player_teams
end

resources :teams do
  resources :player_teams
end

I want to know how I can organize it in the best way so that, once a Player is created, it can choose a Team or create it, to automatically save it in the PlayerTeam table.

    
asked by Gerry 29.08.2017 в 14:11
source

1 answer

0

The association you are using serves you both to choose and to create a Team . The organization of the routes you propose seems more complicated than necessary, since using resources for each model would be more than enough; for example:

resources :players
resources :teams

To create a new Player and choose a Team for it, you would simply do something like this:

Vista (e.g. player.new.html ):

<%= form_for @player do |f| %>
  <!-- campos para crear el 'Player' -->
  <%= collection_select(:team, :name, Team.all, :id, :name)
<% end %>

Driver (e.g. players_controller.rb ):

def create
  @player  = Player.new(player_params)
  @player << Team.find(params[:team_id])

  if @player.save
    # acciones para guardado exitoso
  else
    # acciones para manejo de errores
  end
end

private
def player_params
  params.request(:player).permit(...)
end

To create a Team you would do the same, but instead of using a collection_select you should use fields to send the data of Team and, in the controller you would use something similar to Team.new(team_params) instead of Team.find(:team_id) .

Your question is very open, therefore the answer can not be very detailed without assuming more. I recommend that you take this example and adapt it to your code and, in case you find specific errors, you can post a more detailed question.

    
answered by 29.08.2017 / 15:45
source