设计表格创建belongs_to的关联
问题描述:
我需要用户能够创建在用户注册一个公司:设计表格创建belongs_to的关联
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 %>
我知道以后该怎么处理表单,我只是不知道如何创建表单。
谢谢!
答
如果你想从组现有母公司的使用: -
<%= f.collection_select(:company_id, Company.all, :id, :name) %>
如果你想从用户控制器中创建一个新的公司,只需从PARAMS阅读并创建一个。
@user = User.new(params[:resource_name])
new_company = Company.create(name: params[:resource_name][:company_name])
@user.company_id = new_company.id
@user.save