簡體   English   中英

與Devise模型同時創建關聯的模型

[英]Create associated model at the same time as Devise model

我想在與Devise注冊時創建User的同時創建一個Contractor ,然后將新創建的Contractor與新創建的User關聯。 有什么想法怎么做? (因為我沒錯,所以我無法訪問使用Devise創建用戶的控制器)我應該使用build嗎?如何使用?

我已經閱讀了Devise用戶的個人資料模型嗎? 為Devise用戶 創建配置文件如何 為devise用戶 創建配置文件? 嘗試了幾件事,但我仍然陷於困境。

這是我所擁有的:

視圖-devise / registrations / new.html.erb

<% @title = "Sign up" %>

<div id="main" class="devise-1">
  <div class="container-fluid">
    <div class="row">
      <header class="text-center">
        <h1><%=app_name%></h1>
        <p class="p-0 m-0 text-uppercase">Sign Up</p>
      </header>
    </div>
    <div class="row mt-5">
      <div class="col-12 col-md-6 mr-auto ml-auto">
        <div class="card">
          <div class="card-body">
            <div class="container">
              <% resource.build_contractor %>
              <%= form_for resource, as: resource_name, url: registration_path(resource_name),
                html: { class: "form-horizontal", novalidate: true } do |f| %>
                <%= f.error_notification %>
                <div class="form_group.row">
                  <%= f.fields_for :contractor, class: "row" do |contractor_form| %>
                    <%= contractor_form.label :name, class: "form-label" %>
                    <%= contractor_form.text_field :name, class: "form-control" %>
                  <% end %>
                </div>
                <%= f.form_group :email, class: "row" do |f| %>
                  <%= f.label :email, class: "form-label" %>
                  <%= f.email_field :email, autofocus: true, class: "form-control" %>
                  <%= f.error_messages %>
                <% end %>
                <%= f.form_group :password, class: "row" do |f| %>
                  <%= f.label :password, class: "form-label" %>
                  <%= f.password_field :password, class: "form-control" %>
                  <%= f.error_messages %>
                <% end %>
                <%= f.form_group :password_confirmation, class: "row" do |f| %>
                  <%= f.label :password_confirmation, class: "form-label" %>
                  <%= f.password_field :password_confirmation, class: "form-control" %>
                  <%= f.error_messages %>
                <% end %>
                <div class="row d-flex align-items-center mt-5">
                  <%= link_to "Log in?", new_session_path(resource_name) %>
                  <%= f.submit "Sign up", class: "btn btn-primary ml-auto" %>
                </div>
              <% end %>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

模型-user.rb

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

  has_one :contractor
  accepts_nested_attributes_for :contractor

  has_many :clients, through: :contractor
  has_many :construction_projects, through: :contractor
  # DOES WORK TO CREATE A NEW CONTRACTOR WHEN SIGNING UP BUT CREATES EMPTY CONTRACTORS
  # PER CONTRACTOR OF THE SEED, NEED TO FIND ANOTHER SOLUTION
  # after_create :create_contractor

  # Model validations
  validates_associated :clients
  validates_associated :construction_projects

  validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }

  def option_projects
    unless self.contractor.nil?
      projects = self.contractor.construction_projects.map{ |cp| [cp.name, cp.id] }
      projects << ["Add a new project", "Add a new project"]
      projects
   end
  end

  private
  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation, :remember_me, :user_attributes)
  end

  # DOES WORK TO CREATE A NEW CONTRACTOR WHEN SIGNING UP BUT CREATES EMPTY CONTRACTORS
  # FOR CONTRACTORS OF THE SEED, NEED TO FIND ANOTHER SOLUTION
  # def create_contractor
  #   @contractor = Contractor.create(user: self)
  # end
end

模型-Contractor.rb

class Contractor < ApplicationRecord
  belongs_to :user
  has_many :workgroup_libraries
  has_many :construction_projects, dependent: :destroy
  has_many :clients, dependent: :destroy
  has_many :documents, through: :construction_projects, dependent: :destroy
  has_many :resources
  has_many :resource_quantities, through: :resources

  has_many :workgroups

  mount_uploader :logo, LogoUploader
end

謝謝你的幫助!

您絕對不希望在您的視圖文件中構建承包商。

您可以在User模型上使用ActiveRecord::Callbacks https://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

我建議使用after_create

after_create :generate_contractor

private
def generate_contractor
  # Using the bang method will make sure to raise an error if
  # creating the contractor fails for whatever reason
  contractor.create!(...attributes)
end

另外,如果您想在控制器中執行此操作,則可以執行以下操作: 覆蓋devise registrations控制器

您可以通過在ApplicationController創建after_sign_in_path_for方法來覆蓋默認行為, after_sign_in_path_for方法返回所需頁面的路徑( doc

def after_sign_in_path_for(resource_or_scope)
  @contractor = Contractor.create(contractor_params) 
  current_user
end

在ApplicationController中提供contractor_params方法以清理承包商參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM