在注册时创建公司而不创建公司

时间:2017-07-11 12:53:43

标签: ruby-on-rails ruby devise

您好我有一个简单的应用程序,我希望用户在注册时创建公司。我非常重要的是,用户在注册时创建公司,因此在注册控制器中创建方法

因此,注册表单有4个字段:电子邮件,公司名称,密码和密码确认。

我无法在用户注册表单上查看导致错误的原因。

1 error prohibited this user from being saved:
Company must exist

我的表格如下:

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>
    <div class="field">
    <%= f.label :company %><br />
    <%= f.text_field :company %>
    </div>
  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
在控制台中我得到:

Started POST "/" for 127.0.0.1 at 2017-07-11 21:41:54 +1000
Processing by RegistrationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"l0z2HXJiKtfVFoT9hL6LshiqqOTinqm5GJ0bvhAi/AF6YokwZiZJkvgJXtmt7S/kLPBDFnWNZEzMUhj9FRNPHA==", "user"=>{"email"=>"myemail@gmail.com", "company"=>"test", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameter: company
   (0.2ms)  BEGIN
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "jeremybray.music@gmail.com"], ["LIMIT", 1]]
   (0.2ms)  ROLLBACK
  Rendering devise/registrations/new.html.erb within layouts/application
  Rendered devise/shared/_links.html.erb (1.7ms)
  Rendered devise/registrations/new.html.erb within layouts/application (9.6ms)
  Rendered shared/_navbar.html.erb (1.1ms)
  Rendered shared/_footer.html.erb (1.4ms)
   (0.3ms)  BEGIN
  User Exists (0.8ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "jeremybray.music@gmail.com"], ["LIMIT", 1]]
   (0.3ms)  ROLLBACK
Completed 200 OK in 376ms (Views: 188.1ms | ActiveRecord: 2.2ms)

我新安装了rails 5.02,其中包括两个型号公司和用户(由设计生成)

class Company < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :company
  accepts_nested_attributes_for :company
end

注意我已尝试使用和不使用接受嵌套属性

我的控制器如下

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:fullname,
                                                       company: [:name]])
  end
end

class RegistrationsController < Devise::RegistrationsController

  def create
    super

    if resource.save
      puts params.inspect
      @company = Company.create(name: params[:user][:company])
      resource.update(company_id: @company.id)
      # resource.company_id = @company.id
      # resource.save
    end
  end

  protected

  def update_resource(resource, params)
    resource.update_without_password(params)
  end
end

class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def user_params
    params.require(:user).permit(:fullname, keys: [company: [:name]])
  end

end

我的路线如下

Rails.application.routes.draw do
  devise_for  :users,
              :path => '',
              :path_names => {:sign_in => 'login',
                              :sign_out => 'logout',
                              :edit => 'profile'},
              :controllers => {:registrations => 'registrations'}
  root 'pages#home'

  resources :companies
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

我的架构看起来像是

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20170711100448) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "companies", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.string   "fullname"
    t.integer  "company_id"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["company_id"], name: "index_users_on_company_id", using: :btree
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
  end

end

我还在github上添加了app,只是你需要更多信息:here

2 个答案:

答案 0 :(得分:1)

  

未经许可的参数:公司

根据您的模型和configure_permitted_parameters的外观,您将表单设置为错误。您有accept_nested_attributes_for :company,因此您应该使用fields_for

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>
  <%= f.fields_for :company do |c| %>
    <div class="field">
      <%= c.label :name %><br />
      <%= c.text_field :name %>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
  

1错误禁止此用户被保存:

     

公司必须存在

Rails 5.x 中,belongs_to关联默认为 。但是,您可以使用optional :true来消除错误

belongs_to :company, optional: true

答案 1 :(得分:0)

我在这里做的是在用户上生成迁移,如下所示:

rails g migration AddColumnToUser company:string 

然后使用rake db:migrate

运行迁移

并将:company添加到允许的Devise参数中,以便您可以通过表单访问它。