[英]Rails 4 - Updating Specific Attributes in model
我正在構建一個市場應用程序(第4條),賣家可以在其中列出要出售的商品。 我有一個賣家資料表格,用戶可以在其中輸入有關其品牌的一些詳細信息。
我無法使用用戶輸入來更新記錄。 表單提交無任何錯誤,但模型未更新。
下面的代碼。 在http://mktdemo.herokuapp.com/seller/18上進行演示(登錄:test@test.com / pwd:test1234)
路線:
match "/seller/:id", to: "users#sellerprofile", via: [:get, :put], as: :sellerprofile
我的表格:
<%= form_for(@user, url: sellerprofile_path(id: current_user.id), method: :put, html: { :class => 'edit_profile', :multipart => true }) do |f| %>
<div class="form-group">
<%= f.label :your_story %><i> (required)</i>
<%= f.text_area :profilestory, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :profile_image %><i> (required)</i>
<%= f.file_field :profileimage, class:"form-control" %>
</div>
<div class="form-group">
<%= f.submit class:"btn btn-primary" %>
</div>
<% end %>
user_controller:
def sellerprofile
@user = User.find(params[:id])
@user.update_attributes(:profilestory => params[:profilestory], :profileimage => params[:profileimage])
end
對於圖像,我使用回形針,並在模型中包含has_attached ...代碼。
更新:這是我在控制器中的user_params:
def user_params
params.require(:user).permit(:bankaccname, :profileimage, :profilestory)
end
當我在Sellerprofile方法中使用@user.update(user_params)
時,出現了params :user not found error
。 當我加載表單(不在提交時)時,會發生此錯誤。 錯誤在params.require(:user)
更新2:這是更新方法。 我正在將其用於另一種需要一些銀行帳戶數據的表格,所以我不確定是否可以針對個人資料表格進行修改。
def update
@user.attributes = user_params
Stripe.api_key = ENV["STRIPE_API_KEY"]
token = params[:stripeToken]
recipient = Stripe::Recipient.create(
:name => user_params["bankaccname"],
:type => "individual",
:bank_account => token
)
@user.recipient = recipient.id
respond_to do |format|
if @user.save
format.html { redirect_to edit_user_url, notice: 'Your account was successfully updated.' }
else
format.html { render action: 'edit' }
end
end
end
如果您看您的問題,它說:
當我在Sellerprofile方法中使用@ user.update(user_params)時,出現了params:user not found錯誤。 當我加載表單(不在提交狀態)時,會發生此錯誤
此行告訴我們呈現表單的操作存在問題。 我的意思是您在瀏覽器地址欄中點擊以顯示表單的網址
在您的評論中,您告訴我呈現表單的網址是/seller/:id
,現在讓我們看一下表單代碼
<%= form_for(@user, url: sellerprofile_path(id: current_user.id), method: :put, html: { :class => 'edit_profile', :multipart => true }) do |f| %>
注意到表格中使用的網址了嗎? 您正在使用相同的操作來呈現表單,然后在提交表單后再次將您帶到相同的操作,這是錯誤的。 您應該選擇兩條不同的路線。 一種呈現您的表單,另一種呈現您的表單。 進一步解釋一下,如果您看一下代碼
def sellerprofile
@user = User.find(params[:id])
@user.update_attributes(user_params)
end
因此,當您命中/seller/:id
它將帶您進入Sellerprofile方法,因此您的Sellerprofile方法中的代碼將啟動,並且由於此行@user.update_attributes(user_params)
而嘗試更新您的用戶,但是沒有user_params沒有提交任何表格,所以您得到了一個參數:user not found errorr
固定:
只需執行兩種不同的方法,一種方法可以渲染表單,而另一種方法可以創建記錄:
match "/seller/:id/new", to: "users#sellernew", via: [:get], as: :sellernewprofile
match "/seller/:id", to: "users#sellerprofile", via: [:put], as: :sellerprofile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.