2016-03-04 28 views
0

我有一個下拉菜單,裏面有醫生的名字。我希望能夠從下拉列表中選擇一位醫生,點擊編輯並轉到醫生的編輯頁面。從下拉菜單中選擇,編輯和更新Rails

在我的路線:

resources :physicians, only: [:index, :new, :create, :update] 
    get '/physicians/edit', to: 'physicians#edit' 

在我的私人醫生控制器:

def update 
@physician = Physician.find(params[:id]) 

respond_to do |format| 
    if @physican.update_attributes(physician_params) 
    format.html { redirect_to @physican, info: 'Physician was successfully updated.' } 
    else 
    format.html { render :edit } 
    end 
end 
end 
def physician_params 
    params.require(:physician).permit(:office_id, :user_id, :full_name, :prefix, :first_name, :middle_name, :last_name, :suffix, :primary) 
end 

在我的私人醫生指數:

<%= form_tag '/physicians/edit', :method => :get do %> 

    <%= select_tag :id, options_from_collection_for_select(@physicians, :id, :first_name), 
         prompt: 'Choose one', id: 'physician_select', class: 'form-control option-large' %> 
    <%= submit_tag 'Edit', class: 'btn' %> 
    <% end %> 

在我_form.edit.html.erb

<div class="center" role="form"> 
<%= form_tag physician_path(@physician), :method => :patch do %> 

    <div class="form-group space"> 
    <%= label_tag :first_name %> 
    <%= text_field_tag :first_name, params[:first_name], class: 'form-control' %> 

    </div> 

    <div class="form-group space"> 
    <%= link_to '', root_path, class: 'btn btn-primary glyphicon glyphicon-triangle-left' %> 
    <%= submit_tag 'Update Physician', class: 'btn btn-warning pull-add-btn' %> 
    </div> 
<% end %> 
</div> 
FIRST_NAME屬性:試圖更新時

錯誤

ActionController::ParameterMissing in PhysiciansController#update 
param is missing or the value is empty: physician 

爲first_name的價值是存在的,它被列入白名單了。我不確定發生了什麼事。

+0

你有:在physician_params允許FIRST_NAME?你能分享physician_params方法嗎? – Anand

+0

我已經更新了醫師控制器以顯示允許的參數。 – bradbajuz

+0

我看到你已經轉移到了form_for,這很好。在上面的form_tag代碼中,移除require(:physician)可能會訣竅 - 在form_tag的情況下,params中沒有醫師密鑰。 – Anand

回答

1

因爲您正在更新資源,所以在這種情況下,我會推薦使用form_for而不是form_tagform_tag確實最適合通過POST創建資源,但即使如此,form_for也是一個更方便的解決方案。

您的代碼就變成了:

<%= form_for @physician do |f| %>  
    <div class="form-group space"> 
    <%= f.label :first_name %> 
    <%= f.text_field :first_name, class: 'form-control' %> 
    </div> 

    <div class="form-group space"> 
    <%= link_to '', root_path, class: 'btn btn-primary glyphicon glyphicon-triangle-left' %> 
    <%= f.submit 'Update Physician', class: 'btn btn-warning pull-add-btn' %> 
    </div> 
<% end %> 
+0

我其實更喜歡這個。進行更改,現在得到這個錯誤: PhysiciansController中的NoMethodError#update 未定義的方法'update_attributes'爲零:NilClass – bradbajuz

+0

您的'Physician.find(params [:id])'查找由於某種原因返回爲'nil' 。檢查請求中的參數,確保您在數據庫中爲醫生收到有效的ID。 –

+0

「參數: { 「UTF8」=> 「✓」, 「_method」=> 「補丁」, 「authenticity_token」=> 「xUdMnoBNFj7rTwq1tYag/59gfK0ce + ssQQBhxVUK wIWghJOOkXn + Sd1kiQ9ovjF6icXY/xONq159EeKBNU/K平衡==」, 「physician」=> {「first_name」=>「GEORGE」}, 「commit」=>「更新醫師」, 「id」=>「17」}' – bradbajuz