使用嵌套表单创建用户时 Rails 回滚

2024-02-17

当我尝试将用户添加到我的数据库时,我遇到了回滚,我不确定为什么。

我有三个模型:公司.rb

class Company < ActiveRecord::Base
 acts_as_paranoid

 has_many :locations, dependent: :destroy
 has_many :users, dependent: :destroy
 has_many :tests, through: :locations
 has_many :reports, dependent: :destroy

 accepts_nested_attributes_for :locations, :users

 validates_presence_of :name
end

** 用户.rb **

class User < ActiveRecord::Base
 acts_as_paranoid

 devise :database_authenticatable,
      :recoverable,
      :rememberable,
      :trackable,
      :validatable,
      :registerable

 belongs_to :company
 has_and_belongs_to_many :roles
end

** 位置.rb **

class Location < ActiveRecord::Base
 acts_as_paranoid

 belongs_to :company
 has_many :network_hosts, dependent: :destroy
 has_many :tests, dependent: :destroy
 has_many :commands, dependent: :destroy

 validates_presence_of :company, :identifier, :name
 validates_uniqueness_of :identifier

 delegate :security_percentage, to: :last_test, allow_nil: true

 after_initialize :generate_identifier, if: -> { self.identifier.blank? }

 def generate_identifier
  self.identifier = SecureRandom.uuid.delete("-")
end

因此,当用户想要注册时,他们需要输入公司、位置和用户信息,这些信息由我控制company_controller.rb

** 公司_controller.rb **

class CompanyController < ApplicationController
 def new
  @company = Company.new
  1.times { @company.locations.build }
  1.times { @company.users.build }
 end

 def create
  @company = Company.new(company_params)
  if @company.save
   redirect_to root_url
  else
   render :new
  end
 end

 private

  def company_params
   params.require(:company).permit(:name, locations_attributes: [:name], users_attributes: [:first_name, :last_name, :full_name, :email, :password, :password_confirmation])
  end
end

表格使用标准form_for具有嵌套属性,以便当用户单击提交按钮时我可以一次性完成所有操作

** 公司/new.html.erb **

<%= form_for @company, :url => url_for( :controller => 'company', :action => 'new' ) do |f| %>
  <div class="form-group">
    <%= f.label "Company Name" %>
    <%= f.text_field :name, class: "form-control", placeholder: "ACME Inc."  %>

    <%= f.fields_for :locations do | location_builder | %>
      <%= location_builder.label "Location Name" %>
      <%= location_builder.text_field :name, class: "form-control", placeholder: "Main Building" %>

    <% end %>
  </div>

  <div class="form-group">
    <%= f.fields_for :users do | user_builder | %>
      <%= user_builder.label "First Name" %>
      <%= user_builder.text_field :first_name, class: "form-control", placeholder: "John" %>

      <%= user_builder.label "Last Name" %>
      <%= user_builder.text_field :last_name, class: "form-control", placeholder: "Smith" %>

      <%= user_builder.label "Full Name" %>
      <%= user_builder.text_field :full_name, class: "form-control", placeholder: "John Smith" %>

      <%= user_builder.label "Email" %>
      <%= user_builder.email_field :email, class: "form-control", placeholder: "[email protected] /cdn-cgi/l/email-protection" %>

      <%= user_builder.label "Password" %>
      <%= user_builder.password_field :password, class: "form-control" %>

      <%= user_builder.label "Confirm Password" %>
      <%= user_builder.password_field :password_confirmation, class: "form-control" %>
    <% end %>
  </div>

  <%= f.submit "Submit", class: "btn btn-large btn-success" %>
<% end %>

但是,我在日志中得到回滚,表明这种情况没有发生并且无法找出原因。

Started POST "/signup" for 127.0.0.1 at 2015-08-07 13:49:22 -0400
Processing by CompanyController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"2OHwJ9UfEbfkZHjLdm9BfOd7jlRdvoEz0L4NRJCKl64=", "company"=>{"name"=>"ACME Brick", "locations_attributes"=>{"0"=>{"name"=>"Main House"}}, "users_attributes"=>{"0"=>{"first_name"=>"Testin", "last_name"=>"User", "full_name"=>"Test User", "email"=>"[email protected] /cdn-cgi/l/email-protection", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}, "commit"=>"Submit"}
  User Load (0.8ms)  SELECT  "users".* FROM "users"  WHERE "users"."deleted_at" IS NULL AND "users"."id" = 7  ORDER BY "users"."id" ASC LIMIT 1
  Role Load (0.3ms)  SELECT "roles".* FROM "roles" INNER JOIN "roles_users" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."deleted_at" IS NULL AND "roles_users"."user_id" = $1  [["user_id", 7]]
   (0.1ms)  BEGIN
  Location Exists (0.3ms)  SELECT  1 AS one FROM "locations"  WHERE "locations"."identifier" = '3b7febb35ea740488788d43fcc5e989c' LIMIT 1
  User Exists (0.3ms)  SELECT  1 AS one FROM "users"  WHERE "users"."email" = '[email protected] /cdn-cgi/l/email-protection' LIMIT 1
   (0.1ms)  ROLLBACK
  Rendered company/new.html.erb within layouts/application (5.0ms)
Completed 200 OK in 108ms (Views: 32.2ms | ActiveRecord: 1.9ms | Solr: 0.0ms)

** 公司表 **

class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :name

      t.timestamps
    end
  end
end

** 位置表 **

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|
      t.belongs_to :company, index: true
      t.string :identifier
      t.string :name

      t.timestamps
    end
  end
end

** 用户表 **

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|

      t.belongs_to :company, index: true
      
      t.string :username
      t.string :first_name
      t.string :last_name
      t.string :full_name

      t.string :time_zone, :default => "Central Time (US & Canada)"

      t.string :avatar_file_name
      t.string :avatar_content_type
      t.integer :avatar_file_size
      t.datetime :avatar_updated_at

      ## Database authenticatable
      t.string :email,              :null => false, :default => ""
      t.string :phone_number
      t.string :encrypted_password, :null => false, :default => ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Token authenticatable
      t.string :authentication_token

      t.timestamps
    end

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true

    create_table :roles_users, :id => false do |t|
      t.references :role, :user
    end
  end

  def self.down
    drop_table :users
    drop_table :roles_users
  end
end

** 日志中的错误 **

Started POST "/signup" for 127.0.0.1 at 2015-08-07 18:12:54 -0400
Processing by CompanyController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"aAc83zKKlV4w1i2GhTqTo3ehtXP+tPvYbBBRq1ccYzA=", "company"=>{"name"=>"Test Co.", "locations_attributes"=>{"0"=>{"name"=>"Main"}}, "users_attributes"=>{"0"=>{"first_name"=>"John", "last_name"=>"Smith", "full_name"=>"John Smith", "email"=>"[email protected] /cdn-cgi/l/email-protection", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}, "commit"=>"Submit"}
  User Load (0.5ms)  SELECT  "users".* FROM "users"  WHERE "users"."deleted_at" IS NULL AND "users"."id" = 7  ORDER BY "users"."id" ASC LIMIT 1
  Role Load (0.3ms)  SELECT "roles".* FROM "roles" INNER JOIN "roles_users" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."deleted_at" IS NULL AND "roles_users"."user_id" = $1  [["user_id", 7]]
   (0.1ms)  BEGIN
  Location Exists (0.3ms)  SELECT  1 AS one FROM "locations"  WHERE "locations"."identifier" = '0d759e5405084663a1c110d37f04573a' LIMIT 1
  User Exists (0.2ms)  SELECT  1 AS one FROM "users"  WHERE "users"."email" = '[email protected] /cdn-cgi/l/email-protection' LIMIT 1
   (0.1ms)  ROLLBACK
Completed 422 Unprocessable Entity in 75ms
** [Airbrake] Notice was not sent due to configuration:         
  Environment Monitored? false         
  API key set? true

ActiveRecord::RecordInvalid (Validation failed: Locations company can't be blank):
  app/controllers/company_controller.rb:10:in `create'
  app/controllers/application_controller.rb:95:in `set_time_zone'


  Rendered /Users/godzilla/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.9ms)
  Rendered /Users/godzilla/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)
  Rendered /Users/godzilla/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.2ms)
  Rendered /Users/godzilla/.rbenv/versions/2.1.4/lib/ruby/gems/2.1.0/gems/actionpack-4.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (15.6ms)

它指出位置标识符已经存在,但事实并非如此。这是在尝试创建新内容时即时制作的内容Location(注意方法generate_identifier in the location.rb模型)。最重要的是,该用户也不存在。

有什么想法可以解决这个问题吗?


当你写的时候validates_presence_of :company这意味着您的公司记录在创建位置时必须存在,但尚未完全保存。但是,您的位置仍然与公司对象关联,并且无需进行此验证即可正确保存。我认为您可以验证 company_id 是否存在,因为公司 id 在保存过程中变得可用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用嵌套表单创建用户时 Rails 回滚 的相关文章

  • 如何将html id添加到rails中的form_for标签中?

    我正在尝试将 id 标签添加到我在 Rails 中创建的表单中 表单的开头有以下代码 我是否可以向 form for 嵌入式 ruby 添加一个 id 或者我是否必须创建一个 form tag 字段并在那里添加 id 如果我必须创建 for
  • PHP 电子邮件表单每次刷新页面时都会发送电子邮件

    我的 php 电子邮件每次刷新页面时都会发送电子邮件 例如 用户正在填写表单并使用发送按钮发送 这一切都很好 但如果他们刷新页面 它会再次发送包含所有相同表单信息的电子邮件 我相信这是问题代码 但不知道它是什么 require once c
  • 回形针:样式取决于模型(has_many 多态图像)

    我已将模型设置为使用多态图像模型 这工作正常 但是我想知道是否可以更改每个模型的 styles 设置 找到了一些使用 STI 模型 Art has many images as gt imageable Image belongs to i
  • ruby 管道、IO 和 stderr 重定向

    我希望有一个 ruby 程序 一个 rake 任务 观察另一个 rake 任务的输出 输出写入器输出到 stderr 我想读一下这些行 我很难设置它 如果我有一个作家 stdout writer rb 不断打印一些东西 usr bin en
  • 如何在 Ruby 中创建自定义排序方法

    我想指定一个自定义块方法 通过评估两个属性来对对象数组进行排序 然而 经过多次搜索 我没有找到任何没有的例子 lt gt 操作员 我想比较a to b if a x less than b x return 1 if a x greater
  • 为什么 Rails 应用程序在底部显示数据库信息?

    我创建了一个博客 每当我添加帖子时 帖子索引页面底部总会显示数据库中的记录列表 home html erb 像这样
  • ubuntu 12.04 ruby​​ 2.0 Rails:找不到“thread_safe”

    我正在 ubuntu 12 04 上安装 Rails 使用以下方法手动安装 如何在 Ubuntu 12 04 上正确安装 ruby 2 0 0 https stackoverflow com questions 16222738 how t
  • 为 Rails 上的 postgresql 创建用户

    我选择 postgresql 作为我的 Rails 数据库 但当我尝试运行 rake db create all 时 我遇到了一个明显常见的错误 即 致命 角色 app 不存在 我找到了两种解决方案 但我不确定哪一种是正确的 有一个网站说
  • 在 Yosemite 上安装 Ruby 1.9.2 时出错

    我在 Yosemite 上使用 rvm 安装 ruby 1 9 2 时遇到错误 有人可以帮助我吗 我更新了自制程序和rvm 我正在与其他人合作处理这个项目 所以我无法升级 ruby 我在下面放置了我的输出的链接 提前致谢 Kanyons M
  • Rails3/will_paginate/Ajax - 下一个/上一个链接无法正常工作(这是一个错误吗?)

    我正在遵循 使用ajax分页 http railscasts com episodes 174 pagination with ajax railscast 用于我的 Rails 3 应用程序 一切似乎都运行良好 除了上一个和下一个链接根本
  • 更改 Active Storage 的默认 URL

    我们可以更改从活动存储创建的默认 永久 url 以重定向到 S3 类似于rails active storage representations 我不喜欢网址中的框架名称 Thanks UPDATE 最近 Rails 6 中增加了一个可配置
  • Rails HABTM 设置、模型对象和 join_table 插入控制器设置

    我有以下设置 1 个产品有多个 Product types 许多 Product types 有 1 种类型 根据我对文档的理解 HABTM 关系 我的模型是 class Product lt ApplicationRecord has a
  • 如何检查字符串是否为有效日期

    我有一个字符串 31 02 2010 并想检查它是否是有效日期 最好的方法是什么 我需要一个方法 如果字符串是有效日期 则返回 true 如果不是 则返回 false require date begin Date parse 31 02
  • Calendly 未在 Webflow 中预填写表单

    我在 Webflow 项目中使用 Calendly 并且它有效 不过 我想在 Calendly 中预先填写表格 这里有一个指南 https help calendly com hc en us articles 226766767 Pre
  • 无法在 Sqlite3 中添加默认值为 NULL 的 NOT NULL 列

    尝试将 NOT NULL 列添加到现有表时出现以下错误 为什么会发生这种情况 我尝试了 rake db reset 认为现有记录是问题所在 但即使重置数据库后 问题仍然存在 你能帮我解决这个问题吗 迁移文件 class AddDivisio
  • Rails 4 可安装引擎,找不到文件“jquery”

    我正在创建一个 Rails 可安装引擎插件 它使用 gem jquery rails 我在 gemspec 文件中添加了这段代码 s add dependency jquery rails gt 3 0 1 and run bundle i
  • 如何使用sunspot_rails gem 搜索相关文章

    我有一个迷你博客应用程序 我希望用户查看与他们在文章显示页面中阅读的内容相关的文章 没有 sunspot rails gem 我会做这样的事情 在我的模型中 def self related search query join AND fi
  • 从数组中删除空白元素

    当我从 ruby on Rails 表单中保存多个选择时 它似乎在前面添加了一个空白元素 我该如何删除它 该字段为 selected player utf8 gt authenticity token gt H8W7qPBezubyeU0a
  • 子域中的 Rails url 助手 - 删除子域

    我网站上的用户可以拥有子域 例如 他们的页面网址是 name example com 登录的用户可以查看更多用户信息 因此在用户的显示页面上 我有一个使用以下代码生成的链接 user url user subdomain gt false
  • 查找 Rails 应用程序中未使用的代码

    如何查找正在运行和未运行的代码生产中 该应用程序经过充分测试 但还有很多测试unused代码 因此 他们在运行测试时得到覆盖 我想重构并清理这个烂摊子 它一直在浪费我的时间 我有很多后台工作 这就是为什么我希望生产环境来指导我 在 Hero

随机推荐