与设计模型同时创建关联的模型

时间:2018-12-12 13:16:04

标签: ruby-on-rails devise

我想在与Contractor进行注册时同时创建一个User,然后将一个新创建的Devise与该{新创建的Contractor。有什么想法怎么做? (因为我没错,所以我无法访问使用Devise创建用户的控制器)我应该使用build,如何使用?

我已经读过Profile model for Devise users?Creating Profile for Devise usersHow to create a profile for devise user?,并尝试了几种方法,但是我仍然很困惑。

这是我所拥有的:

视图-devise / registrations / new.html.erb

User

模型-user.rb

<% @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>

模型-Contractor.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

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您绝对不想在视图文件中构建承包商。

您可以在ActiveRecord::Callbacks模型上使用User 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

或者,如果您想在控制器中执行此操作,则可以执行以下操作:Override devise registrations controller

答案 1 :(得分:0)

您可以通过在after_sign_in_path_for中创建一个ApplicationController方法来覆盖默认行为,并让该方法返回所需页面的路径(doc

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

在ApplicationController中提供contractor_params方法以清理承包商参数。