Has_many / belongs_to关系不起作用

时间:2014-05-11 14:53:30

标签: ruby-on-rails

嗯,有:

播放器型号:

class Player < ActiveRecord::Base
  belongs_to :team
end

团队模型:

class Team< ActiveRecord::Base
  has_many :players

  def to_s
    return name    # use whatever you want to be displayed. 
  end
end

玩家的视图:

<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 %>

来自玩家控制器的方法

  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 

不幸的是,在添加了一名玩家(并从下拉菜单为他挑选团队)后,我被重定向到了玩家的显示视图,并且没有关于玩家团队的任何信息。就像没有添加关于团队的信息一样

<p>
  <strong>Name:</strong>
  <%= @player.name %>
</p>

<p>
  <strong>Lastname:</strong>
  <%= @player.lastname %>
</p>

<p> 
  <strong>Team:</strong>
  <%= @player.team %>
</p>

也许有些人可以帮我找到错误。感谢。

编辑:

我的整个玩家的控制器文件

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

我的路线:

Rails.application.routes.draw do
  get 'public/home'
  get 'public_controller/home'
    resources :players
    resources :teams
end

3 个答案:

答案 0 :(得分:2)

您的控制器操作不正确:

  def new
    @player = Player.new
    @teams = Team.all
  end

  def create
    @player = Player.new(params[:player])
    @player.save
    redirect_to @player
  end

答案 1 :(得分:0)

变化

class Player < ActiveRecord::Base
  belongs_to :Team
end

class Player < ActiveRecord::Base
  belongs_to :team
end

答案 2 :(得分:0)

您的控制器应如下所示

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

如果是拼写错误,请尝试将form_for的第一行更改为

<%= form_for @player,url: players_path(@player) do |f| %>