Form_for不将数据保存到数据库

时间:2019-02-20 17:41:35

标签: ruby-on-rails ruby form-for

我一生无法弄清楚我的代码在做什么错。我有一个form_for,但是单击“保存”时,它不会保存表单中的数据,而不会保存控制器中的数据。

控制器:

class RegistersController < ApplicationController

  def index

  end

  def new
    @reg = Register.new
  end

  def create
    @reg = Register.new(params.permit(:user, :user_id, :class_id))
    @reg.user_id = current_user.id

    @reg.save
  end

  def update

  end
end

新功能:

<%= form_for @reg do |f| %>
  <div class="form-group">
    <%= f.label :class_name, class: "col-sm-2 control-label" %>
    <%= f.text_area :class_name, class: "form-control"%>
  </div>
  <div class="form-group">
    <%= f.label :user, class: "col-sm-2 control-label" %>
    <%= f.text_area :user, class: "form-control" %>
  </div>
  <%= f.submit 'Save', class: 'btn btn-primary btn-block' %>
<% end %>

型号:

class Register < ApplicationRecord
  belongs_to :user, optional: true
  belongs_to :event, optional: true
end

编辑:

我进一步弄乱了,然后来到了这里:
@reg = Register.new(params.required(:user).permit(:user_id,:class_name))

这是给我的日志:

    Processing by RegistersController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"BJr3T+RiI0YiyixC6EORKtMG3L8Q9LP3kL7Dh4apt0WdeGzN5mVhy/oNn64+xF9TRRztLqL5/Hf6WEwhucRF8w==", "register"=>{"class_name"=>"Toddler", "user"=>"Billy"}, "commit"=>"Save"}
    Completed 400 Bad Request in 1ms (ActiveRecord: 0.0ms)



ActionController::ParameterMissing (param is missing or the value is empty: user):

1 个答案:

答案 0 :(得分:0)

只要喜欢:

  def create
    @reg = Register.new(params.required(:register).permit(:user_id, :class_name))
    @reg.user_id = current_user.id
    @reg.save! # This will raise exception if something is wrong
  end

顺便说一句,仅适用于TDD / BDD概念即可消除此类问题。这个过程非常简单。