Reputation: 3152
Well, there is:
A player model:
class Player < ActiveRecord::Base
belongs_to :team
end
and a team model:
class Team< ActiveRecord::Base
has_many :players
def to_s
return name # use whatever you want to be displayed.
end
end
Player's new view:
<h1>New player</h1>
<%= form_for :player, url: players_path do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :lastname %><br>
<%= f.text_field :lastname %>
</p>
<p>
Klub</br>
<%= f.collection_select :Team, @teams, :to_s, :to_s %>
</p>
<p>
<%= f.submit%>
</p>
<% end %>
and methods from player's controller:
def new
@teams = Team.all
end
def create
@player = Player.new(player_params)
@player.save
redirect_to @player
end
private
def player_params
params.require(:player).permit(:name, :lastname, :team)
end
Unfortunately, after adding a player (and chosing team for him from drop down menu), i get redirected to player's show view and there isn't any info about player's team. Like the info about the team was not added
<p>
<strong>Name:</strong>
<%= @player.name %>
</p>
<p>
<strong>Lastname:</strong>
<%= @player.lastname %>
</p>
<p>
<strong>Team:</strong>
<%= @player.team %>
</p>
Maybe some of you could help me with finding an error here. Thanks.
edit:
my whole player's controller file
class PlayerController < ApplicationController
def new
@teams = Team.all
end
def create
@player = Player.new(player_params)
@player.save
redirect_to @player
end
def show
@player = Player.find(params[:id])
end
def index
@player = Player.all
end
private
def player_params
params.require(:player).permit(:name, :lastname, :team)
end
end
my routes:
Rails.application.routes.draw do
get 'public/home'
get 'public_controller/home'
resources :players
resources :teams
end
Upvotes: 0
Views: 64
Reputation: 33552
Your controller should look like this
def new
@player = Player.new
@teams = Team.all
end
def create
@player = Player.new(player_params) #here i guess its a typo
@player.save
redirect_to @player
end
private
def player_params
params.require(:player).permit(:name, :lastname, :team)
end
Well if its a typo,then try changing your first line of your form_for
to
<%= form_for @player,url: players_path(@player) do |f| %>
Upvotes: 0
Reputation: 514
you controller actions are not correct:
def new
@player = Player.new
@teams = Team.all
end
def create
@player = Player.new(params[:player])
@player.save
redirect_to @player
end
Upvotes: 2
Reputation: 514
change
class Player < ActiveRecord::Base
belongs_to :Team
end
to
class Player < ActiveRecord::Base
belongs_to :team
end
Upvotes: 0