Devise: User belongs_to organization

后端 未结 1 1384
温柔的废话
温柔的废话 2021-02-03 14:21

I am using devise for authentication, and on the Sign Up page I have a text field for \'organization\' so when the user signs up, they will create an organization, and I want th

1条回答
  •  萌比男神i
    2021-02-03 15:08

    You can use accepts_nested_attributes_for in your User model (documentation)

    It should look like:

    class User < ActiveRecord::Base
      belongs_to :organization
      accepts_nested_attributes_for :organization
    end
    
    class Organization < ActiveRecord::Base
      has_many :users
    end
    

    In views you could use Rails helper or create field by hand:

    
    
    <% user = User.new(organization => Organization.new) %>
    <%= form_for user do |form| %>
      <%= form.fields_for user.organization do |organization_form| %>
        <%= organization_form.text_field :name %>
      <% end %>
    <% end %>
    

    EDIT: Your devise view should look like:

    Sign up

    <% resource.organization ||= Organization.new %> <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= devise_error_messages! %>
    <%= f.label :email %>
    <%= f.email_field :email %>
    <%= f.fields_for resource.organization do |organization_form| %>
    <%= organization_form.label :name %>
    <%= organization_form.text_field :name %>
    <% end %>
    <%= f.label :password %>
    <%= f.password_field :password %>
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation %>
    <%= f.submit "Sign up" %>
    <% end %> <%= render :partial => "devise/shared/links" %>

    0 讨论(0)
提交回复
热议问题