【问题标题】:Devise Form for create belongs_to association为创建 belongs_to 关联设计表单
【发布时间】:2017-05-07 10:12:56
【问题描述】:

我需要用户能够在用户注册中创建公司:

class Company < ActiveRecord::Base
  has_many: :users
end

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable,
     :confirmable

  belongs_to :company
end

和形式:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { role: 'form' }) do |f| %>
  <div class="form-group">
    <%= f.label :company_name %>
    **** how to add company name? ****
  </div>
  <div class="form-group">
    <%= f.label :email %>
    <%= f.email_field :email, autofocus: true, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>
  </div>
  <%= f.submit t('.sign_up', default: 'Sign up'), class: 'btn btn-primary' %>
<% end %>

我知道以后如何处理表单,我只是不知道如何创建表单。

谢谢!

【问题讨论】:

    标签: ruby-on-rails devise nested-forms


    【解决方案1】:

    如果你想使用来自现有母公司的集合:-

    <%= f.collection_select(:company_id, Company.all, :id, :name) %>
    

    如果您想从用户控制器中创建一个新公司,只需从参数中读取并创建一个。

    @user = User.new(params[:resource_name])
    new_company = Company.create(name: params[:resource_name][:company_name])
    @user.company_id = new_company.id
    @user.save
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-09
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多