簡體   English   中英

單擊表單上的提交后,Rails自動更新數據庫屬性

[英]Rails auto update database attribute after clicking submit on a form

我在rails中使用simple_form來創建某些事件。 要創建新事件,您需要以用戶身份登錄。 該表格將要求用戶輸入事件名稱,開始日期和結束日期。 當用戶單擊提交按鈕時,我希望表單自動更新數據庫中的屬性user_id。

現在在數據庫中,事件表中的user_id字段始終設置為null。 但是我需要將此屬性設置為:

events.user_id = current_user.id

這是我的事件表,以獲取更多信息: 在此處輸入圖片說明

注意:我在此數據庫中手動輸入了user_id的值。

問題:用戶單擊提交后,如何更新數據庫屬性? 還是有一種默認的方式來在創建新事件時始終設置user_id?

這是new.html.erb事件視圖中的代碼

<%= simple_form_for(@event) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :name %>
    <%= f.input :start_at %>
    <%= f.input :end_at %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

在事件控制器的create方法中,添加

events.user_id = current_user.id

保存之前。

例如,如果使用@event = Event.new(params[:event])創建事件(在def create方法中), @link.user_id = current_user.id on the next line執行@link.user_id = current_user.id on the next line
您可能可以執行@link.user = current_user而rails會找出ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM