保存表单时意外回滚

时间:2016-12-13 02:26:56

标签: ruby-on-rails activerecord ruby-on-rails-5 nested-attributes rollback

我在使用嵌套属性保存表单时遇到了一些问题。我正在使用两个模型SubmissionTag。每个Submission has_one :tag

我遇到的问题是,当我提交表单时,我收到“回滚”并且数据未保存:

Processing by SubmissionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"XSGZaJ1nR2MbkJJZS/Ftkb9jefb9FLOAJPA1nYbG/AIrVJYb93DtPxc7fzhUFt9uSnzzcNGqkMTSz/jFsFejHA==", "submission"=>{"domain"=>"test", "tag_attributes"=>{"tag_text"=>"Junk Science", "notes"=>"test"}}, "commit"=>"Submit"}
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
  Rendering submissions/new.html.erb within layouts/application
  Rendered submissions/_form.html.erb (10.6ms)
  Rendered submissions/new.html.erb within layouts/application (11.8ms)
  Rendered shared/_navbar.html.erb (2.7ms)
Completed 200 OK in 2276ms (Views: 2269.6ms | ActiveRecord: 0.2ms)

我的控制器如下:

  def new
    @submission = Submission.new
    @tag = @submission.build_tag
  end

  def create
    @submission = Submission.new(submission_params)

    if @submission.save
      redirect_to root_path, notice: "Thank you for your submission."
    else
      render 'new'
    end
  end

  private

  def submission_params
    params.require(:submission).permit(:subtitle, :domain, :type1, :type2, :type3, :website_type, :user_id, :notes, tag_attributes:[:tag_text, :notes])
  end

我的表格如下:

<%= simple_form_for @submission, defaults: { wrapper_html: {class: 'form-group'}, input_html: { class: "form-control" }} do |f| %>

    <%= f.input :domain, required: true, input_html: {class: "form-control"}%>
    <%= f.simple_fields_for :tag do |tag| %>
      <%= tag.input :tag_text, collection: source_type %>
      <%= tag.input :notes %>
    <% end %>

    <%= f.submit "Submit", class: 'btn btn-primary'%>
<% end %>

感谢您的任何建议。

更新1: logger.debug @submission.errors.inspect的输出如下:

 #<ActiveModel::Errors:0x007ff49e5f8e90 @base=#<Submission id: nil, domain: "test", type1: nil, type2: nil, type3: nil, website_type: nil, user_id: nil, notes: nil, created_at:     nil, updated_at: nil>, @messages={:"tag.submission"=>["must exist"]}, @details={"tag.submission"=>[{:error=>:blank}]}>

submission下有很多空白字段,但在我尝试添加嵌套属性之前,它并没有开始投放。

UPDATE2: 我的Tag模型如下:

class Tag < ApplicationRecord
  belongs_to :submission
end

我的Submission模型如下:

class Submission < ApplicationRecord
    has_one :tag
    accepts_nested_attributes_for :tag
end

1 个答案:

答案 0 :(得分:0)

最终,我只是将rails版本恢复为Rails4和所有内容。工作