播放器不会显示已添加

时间:2018-02-06 21:32:59

标签: html ruby-on-rails ruby

我正在尝试添加一个新的播放器,但它不会显示,我会继续回滚。我已经尝试将hidden_​​field用于我的user_id但它似乎没有做任何事情。这样做还有其他选择吗?我很确定它的东西很小,我不得不改变。请帮忙。

玩家控制器:

def new
        @players = Player.new
    end

def create
        @players = Player.create(user_id: params[:player][:user_id], first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
        redirect_to players_path
    end

玩家新:

<h1>Add a new Player</h1>

<%= form_for @players do |f| %>

<p>First Name   <%= f.text_field :first_name %></p>

<p>Last name    <%= f.text_field :last_name %></p>

<p>Position <%= f.text_field :position %></p>

<p>Favorite Team(optional)  <%= f.text_field :favorite_team %></p>

<p>Extra Equipment  <%= f.text_field :extra_equipment %></p>

<p>Bio  <%= f.text_field :bio %></p>

<%= f.hidden_field :user_id %>

<%= submit_tag "Add"%>

<% end %>

玩家模型

class Player < ApplicationRecord
    belongs_to :user
    has_many :pickup, through: :player_pickup
end

2 个答案:

答案 0 :(得分:1)

对于crud(创建,更新,检索和销毁),请使用@player,而不是@players。 另外,从私有方法调用你的params而不是直接调用它,这是rails中的DRY概念。

所以它会以某种方式(例如):

def new
 @player = Player.new
end

def create
 @player = Player.new(player_params)
 if @player.save 
  // Do something
 else
  // Do something
 end
end

private

def player_params
 params.require(:player).permit(:param_1, :param_2 .... etc)
end
在您的视图中

然后使用form_for @player

答案 1 :(得分:0)

您没有将值传递到隐藏字段。你应该做像

这样的事情

<%= f.hidden_field :user_id, value: current_user.id %>

如果user_id始终是current_user - 您不需要字段,则可以在控制器中分配它。

 def create
  @players = Player.create(first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
  @players.user_id = current_user.id
  @players.save
    redirect_to players_path
end

或者 - 如果你想保持相同的格式

def create
   @players = Player.create(user_id: current_user.id, first_name: params[:player][:first_name], last_name: params[:player][:last_name], position: params[:player][:position], favorite_team: params[:player][:favorite_team], extra_equipment: params[:player][:extra_equipment], bio: params[:player][:bio])
    redirect_to players_path
end