使用不同参数进行路由不能更新

时间:2016-10-24 04:03:14

标签: ruby-on-rails ruby-on-rails-4

我没有使用默认的id参数,而是使用playerId重新路由。一切都按原样运行,但在更新播放器记录时,它会路由回id而不是playerId并显示此错误undefined method更新'为nil:NilClass`。

路线

resources :players, param: :playerId

控制器

def update
    respond_to do |format|
      if @player.update(player_params)
        format.html { redirect_to @player, notice: 'Player was successfully updated.' }
        format.json { render :show, status: :ok, location: @player }
      else
        format.html { render :edit }
        format.json { render json: @player.errors, status: :unprocessable_entity }
      end
    end
  end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_player
      @player = Player.find_by(playerId: params[:playerId])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def player_params
      params.require(:player).permit(:playerId, :first_name, :last_name, :teamId,:image)
    end

表格

<%= form_for(@player) do |f| %>
    <%= f.label :playerId %><br>
    <%= f.number_field :playerId %>
    <%= f.label :first_name %><br>
    <%= f.text_field :first_name %>
    <%= f.label :last_name %><br>
    <%= f.text_field :last_name %>
    <%= f.label :teamId %><br>
    <%= f.collection_select(:teamId, Team.all, :teamId, :name, { :prompt => 'Team Select', :selected => @player.teamId }) %>
    <%= f.label :image %><br>
    <%= f.file_field :image %>
    <%= f.submit %>
<% end %>

路线

         root GET    /                                 pages#home
      players GET    /players(.:format)                players#index
              POST   /players(.:format)                players#create
   new_player GET    /players/new(.:format)            players#new
  edit_player GET    /players/:playerId/edit(.:format) players#edit
       player GET    /players/:playerId(.:format)      players#show
              PATCH  /players/:playerId(.:format)      players#update
              PUT    /players/:playerId(.:format)      players#update
              DELETE /players/:playerId(.:format)      players#destroy

0 个答案:

没有答案