2016-02-27 114 views
0

我一直在創建一個系統,我創建這些條目,但問題是當我試圖創建編輯功能,它不更新帖子,但創建一個新的。更新功能不更新帖子,但創建一個新帖子

我控制器文件看起來像這樣:

class BetsController < ApplicationController 
    def new 
    @bet = Bet.new 
    end 

    def create 
    @bets = Bet.new(bet_params) 

    if @bets.save 
     flash[:success] = 'Bet Successfull Logged.' 
     redirect_to new_bet_path 
     else 
     flash[:danger] = 'Error, Bet has not been logged. Try again mate.' 
     redirect_to new_bet_path 
     end 
    end 

    def show 
    @bet = Bet.find(params[:id]) 
    end 

    def edit 
    @bet = Bet.find(params[:id]) 
    end 

    def update 
    @bet = Bet.find(params[:id]) 

     if @bet.update_attributes(bet_params) 
      flash[:success] = "Bet Updated!" 
      redirect_to bet_path(params[:id]) 
     else 
      render action: :edit 
     end 
    end 

    private 

    def bet_params 
     params.require(:bet).permit(:bet_placed, :game, :units_placed, :odds, :profit_or_loss) 
    end 

end 

而且也被提交看起來像這樣的形式:

<%= form_for :bet, url: bets_path, :html => { :multipart => true } do |f| %> 

    <p class="form-group"> 
    <%= f.label :bet_placed %><br> 
    <%= f.text_field :bet_placed, class: 'form-control' %> 
    </p> 

    <p class="form-group"> 
    <%= f.label :game %><br> 
    <%= f.text_field :game, class: 'form-control' %> 
    </p> 

    <p class="form-group"> 
    <%= f.label :units_placed %><br> 
    <%= f.text_field :units_placed, class: 'form-control' %> 
    </p> 

    <p class="form-group"> 
    <%= f.label :odds %><br> 
    <%= f.text_field :odds, class: 'form-control' %> 
    </p> 

    <p class="form-group"> 
    <%= f.label :profit_or_loss %><br> 
    <%= f.text_field :profit_or_loss, class: 'form-control' %> 
    </p> 

    <%= f.submit 'Update Profile', class: 'btn btn-default' %> 

<% end %> 

回答

0

根據導軌自然路徑,路徑bets_path始終轉到create方法。由於更新需要一個ID,而你沒有給它,它會創建。

變化形式,

<%= form_for @bet, :html => { :multipart => true } do |f| %> 
 

 
    <p class="form-group"> 
 
    <%= f.label :bet_placed %><br> 
 
    <%= f.text_field :bet_placed, class: 'form-control' %> 
 
    </p> 
 

 
    .................... 
 

 
    <p class="form-group"> 
 
    <%= f.label :profit_or_loss %><br> 
 
    <%= f.text_field :profit_or_loss, class: 'form-control' %> 
 
    </p> 
 

 
    <%= f.submit 'Update Profile', class: 'btn btn-default' %> 
 

 
<% end %>

作爲參考,

HTTPVerb Path \t  controller#Action \t Named Helper 
 
GET \t   /bets \t bets#index \t  bets_path 
 
GET \t  /bets/new \t bets#new \t  new_bet_path 
 
POST \t /bets \t  bets#create \t  bets_path 
 
GET \t  /bets/:id \t bets#show \t   bet_path(:id) 
 
GET \t  /bets/:id/edit \t bets#edit \t  edit_bet_path(:id) 
 
PATCH/PUT /bets/:id \t bets#update \t   bet_path(:id) 
 
DELETE \t /bets/:id \t bets#destroy \t  bet_path(:id)

1

表單目前正在安裝,它會一直打到create方式行動。如果你改變你的form_for以下它應該工作

<%= form_for @bet do |f| %> 
... 
<% end %> 

你不應該需要multipart => true要麼因爲你的形式沒有任何文件的輸入。