0

I am making a website for an existing database. This database is from a game and I can't make many changes in the existing tables.

I decided to use Devise as the authentication solution. I will use the User model from Devise for the website and the database has a Login table with some important informations.

They will have a one to one association where the User has_one Login and the Login belongs to User.

I changed the User registration form to have some Login information. I used nested form for that. When I signup it should create the User and Login.

I'm trying this create part but it's not working. I tried many different ways but it never works. The two main problems are:

  1. it creates the User but do not create the Login
  2. it creates both but the Login does not have the information that i put in the form. They are all blank

I tried many different ways:

  • override the new method in the RegistrationController using resource.build_login
  • override sign_up_params method with permit inside
  • put the resource.build_login in the new view
  • override build_resource and put resource.build_login there

None of them works.

I'm using Rails 5.0.2 and Devise 4.2.0.

These are the models:

class Login < ApplicationRecord
  belongs_to :user
  # accepts_nested_attributes_for :user
end

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable

  has_one :login
  # accepts_nested_attributes_for :login
end

One important question is where should I put the accepts_nested_attributes_for? I saw people using it in the Model that has belong and I also saw people using in the has_one model.

This is my RegistrationController:

class Users::RegistrationsController < Devise::RegistrationsController
  def new
    super
    resource.build_login
  end
  def create
    super
  end
  def sign_up_params
    params.require(resource_name).permit(:email, :password, 
                   :password_confirmation, login_attributes:  
                   [:userid, :birthdate, :sex])
  end
end

And this is my view:

<%= simple_form_for(resource, as: resource_name, url: 
                    registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>
  <%= f.input :email, required: true, autofocus: true, class: 'form-
              control' %>
  <%= f.input :password, required: true, hint: ("No mínimo #
              {@minimum_password_length} caracteres" if 
               @minimum_password_length) %>
  <%= f.input :password_confirmation, required: true %>
  <%= f.simple_fields_for :login do |ff| %>
    <%= ff.input :userid %>
    <%= ff.input :birthdate %>
    <%= ff.label :sex %>
    <%= ff.input_field :sex, collection: [['Feminino', 'F'], 
               ['Masculino', 'M']], class: 'form-control' %>
  <% end %>
  <%= f.button :submit, 'Cadastrar', class: 'btn btn-primary' %>
<% end %>

I hope that all the information needed are there.

Most answers I found for this problem were to Rails 4 or Rails 3 and maybe they didn't work for me because I'm using Rails 5.

Edit #1: Added create method in RegistrationController.

Edit #2: With accepts_nested_attributes_for in user the fields doesn't appear so I changed accepts_nested_attributes_for to login model.

And here is the log for how the code is now:

Started POST "/users" for 127.0.0.1 at 2017-07-14 20:24:40 -0300
Processing by Users::RegistrationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>
      "habj5iep5SaE5nkyimzFyVslsCAIvy7ZokmM
       KA8WDgbgQkYCa/mofo83sllRiwX13OCkPXIjbkR+CcDKBICXOw==",
       "user"=>{"email"=>"breno@gmail.com", "password"=>"[FILTERED]", 
       "password_confirmation"=>"[FILTERED]", "login"=>
      {"userid"=>"breno1", "birthdate"=>"13/07/2017", "sex"=>"M"}}, 
       "commit"=>"Cadastrar"}
Unpermitted parameter: login
(10.8ms)  BEGIN
User Exists (10.1ms)  SELECT  1 AS one FROM `users` WHERE 
  `users`.`email` = BINARY 'breno@gmail.com' LIMIT 1
SQL (11.5ms)  INSERT INTO `users` (`email`, `encrypted_password`, 
  `created_at`, `updated_at`) VALUES ('breno@gmail.com', 
  '$2a$11$4le6ZB5JyrYZGYLXvtlwa.c6BA463BvNYkSINfU0C10LoJADEYJ8q', 
  '2017-07-14 23:24:41', '2017-07-14 23:24:41')
(18.3ms)  COMMIT
(12.6ms)  BEGIN
SQL (11.0ms)  UPDATE `users` SET `sign_in_count` = 1, 
  `current_sign_in_at` = '2017-07-14 23:24:41', `last_sign_in_at` = 
  '2017-07-14 23:24:41', `current_sign_in_ip` = '127.0.0.1', 
  `last_sign_in_ip` = '127.0.0.1' WHERE `users`.`id` = 33
(11.6ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 436ms (ActiveRecord: 85.8ms)


Started GET "/" for 127.0.0.1 at 2017-07-14 20:24:41 -0300
Processing by HomeController#index as HTML
Rendering home/index.html.erb within layouts/application
Rendered home/index.html.erb within layouts/application (0.7ms)
User Load (13.7ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` 
  = 33 ORDER BY `users`.`id` ASC LIMIT 1
Login Load (11.1ms)  SELECT  `login`.* FROM `login` WHERE 
  `login`.`user_id` = 33 LIMIT 1
Rendered layouts/_side_navbar.html.erb (26.0ms)
Completed 500 Internal Server Error in 619ms (ActiveRecord: 24.8ms)



ActionView::Template::Error (undefined method `userid' for 
  nil:NilClass):
4:       <div class="sidenav-header-inner text-center">
5:         <%= image_tag 'avatar-1.jpg', class: 'img-fluid rounded-
    circle' %>
6:         <h2 class="h5 text-uppercase">
7:           <%= current_user.login.userid %>
8:         </h2>
9:         <span class="text-uppercase">
10:           <%= current_user.is_admin? ? 'administrador' : 'jogador' 
    %>

app/views/layouts/_side_navbar.html.erb:7:in 
`_app_views_layouts__side_navbar_html_erb__415501206315934300_
    70011534596860'
app/views/layouts/application.html.erb:13:in 
`_app_views_layouts_application_html_erb__1458307398416558594_
    70011827322320'
Rendering /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    template_error.html.erb within rescues/layout
Rendering /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _source.html.erb
Rendered /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _source.html.erb (32.9ms)
Rendering /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _trace.html.erb
Rendered /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _trace.html.erb (5.0ms)
Rendering /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _request_and_response.html.erb
Rendered /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    _request_and_response.html.erb (1.7ms)
Rendered /home/prikster/.rvm/gems/ruby-2.3.1/gems/actionpack-
    5.0.2/lib/action_dispatch/middleware/templates/rescues/
    template_error.html.erb within rescues/layout (62.6ms)

Is accepts_nested_attributes_for in the right model?

In the log there is a line pointing to an Unpermitted parameter: login. What should I do to correct this?

1 Answers1

1

I solved my problem.

I just had to add a required: false to Login's relation with User.

My Login model is like this now:

class Login < ApplicationRecord
  belongs_to :user, required: false
end

I think the problem was when it tried to create/save Login the User didn't had the id yet.

In the end both models are created, with relation between them and they both have their attributes with their right values.

  • Yes. this is why I would recommend you to read the following: https://stackoverflow.com/questions/17767449/rails-4-0-with-devise-nested-attributes-unpermited-parameters and Devise Wiki: – Stephane Paquet Jul 15 '17 at 03:20