简体   繁体   English

单击表单上的提交后,Rails自动更新数据库属性

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

I am using simple_form in rails to create certain events. 我在rails中使用simple_form来创建某些事件。 To create a new event, you are required to login as a user. 要创建新事件,您需要以用户身份登录。 The form will ask the user to enter the event name, start date, and end date. 该表格将要求用户输入事件名称,开始日期和结束日期。 When the user clicks the submit button, I want the form to automatically update the attribute user_id in the database. 当用户单击提交按钮时,我希望表单自动更新数据库中的属性user_id。

Right now in the database, the user_id field in the events table is always set to null. 现在在数据库中,事件表中的user_id字段始终设置为null。 However I need this attribute to be set to: 但是我需要将此属性设置为:

events.user_id = current_user.id

Here is my events table for more info: 这是我的事件表,以获取更多信息: 在此处输入图片说明

Note: I manually entered the values for user_id in this database. 注意:我在此数据库中手动输入了user_id的值。

Question: How do I update a database attribute, after a user clicks submit? 问题:用户单击提交后,如何更新数据库属性? Or is there a default way of always setting the user_id when a new event is created? 还是有一种默认的方式来在创建新事件时始终设置user_id?

Here is the code in the new.html.erb events view 这是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 %>

In your create method in your event controller, add your 在事件控制器的create方法中,添加

events.user_id = current_user.id

before the save. 保存之前。

eg if you create the event (in the def create method) with @event = Event.new(params[:event]) then do @link.user_id = current_user.id on the next line 例如,如果使用@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
You can probably do @link.user = current_user and rails will figure the id out. 您可能可以执行@link.user = current_user而rails会找出ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM