Develop: user belongs to organization

I use the program for authentication, and on the "Registration" page I have a text box for "organization", so when a user signs up, they will create an organization and I want the user to be associated with this organization (the user model has the attribute organization_id). I created development views and added a field name for the organization name. In my models, I have User belongs_to: organization and organization has_many: users (more than one user will be created associated with the organizations). I was on all the paths that I could find, trying to do this without changing the controller, but no luck. Please do not offer to do this without changing the controller, unless you have an example application in which you have implemented it, to which you can point.

I created a registration controller as described here: Override application registration controller

I just threw a few puts instructions in the controller, and I don’t see them being displayed on the console, so it seems like I am not getting to this controller.

I also copied my views from the application / view / development / registration into the application / view / registration, after which my views seem to come from space! The organization field that I created more is not displayed, and I cannot tell where the view is loading from.

Sorry for not being shorter, but I'm not sure where to go with this.

+4
source share
1 answer

You can use accepts_nested_attributes_for in your user model ( documentation )

It should look like this:

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

In views, you can use the Rails helper or create a field manually:

 <input type="text" name="user[organization_attributes][name]"> <% 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 design should look like this:

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

Source: https://habr.com/ru/post/1379380/


All Articles