mercredi 9 mars 2016

NoMethodError - undefined method for a nested form from a join table using devise registration

I'm following this tutorial on how to nest other Models in my Devise registration form. I'm getting an error in my New controller 'undefined method `languages_user=' for #'. Languages_Users is a join table, and I'm wondering if this is the reason it isn't working, but I don't understand what the solution is. I want to add 2 different records of Languages_Users when the user signs up.

Controllers: languages_users_controller.rb

class LanguagesUsersController < ApplicationController
    before_action :authenticate_user!
    before_action :set_languages_user, only: [:show, :edit, :update, :destroy]

    def new
        @users = LanguagesUser.where(:user_id => current_user.id).count
        @user_count = @users
        @languages_user = LanguagesUser.new
    end

    def create
        @languages_user = LanguagesUser.new(languages_user_params)
        @languages_user.user_id = current_user.id

        respond_to do |format|
          if @languages_user.save
            format.html { redirect_to new_languages_user_path, notice: 'Proficiency was successfully created.' }
            format.json { render :show, status: :created, location: @languages_user }
          else
            format.html { render :new }
            format.json { render json: @languages_user.errors, status: :unprocessable_entity }
          end
        end
  end

  private
def set_languages_user
  @languages_user = LanguagesUser.find(params[:id])
end

def languages_user_params
  params.require(:languages_user).permit(:language_id, :level, :user_id)
end
end

registrations_controller.rb

 class Users::RegistrationsController < Devise::RegistrationsController

  def new
    build_resource({})
     self.resource.languages_user = LanguagesUser.new[sign_up_params]
    respond_with self.resource
  end
 def create
    @user_id = current_user.id
    super
 end

 def sign_up_params
    allow = [:email, :password, :password_confirmation, [languages_user_attributes: [:language_id, :user_id, :level]]]
  end
end

Relevant sections of User's new.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
   <%= f.fields_for :langauges_user do |lu| %>
      <%#= lu.text_field :language_id %>
      <%= lu.collection_select(:language_id, Language.order('language ASC').all, :id, :language) %><br>
      <%= lu.hidden_field languages_user[level], value: 1 %>
    <% end %>
    <%= f.submit "Sign up" %>
 <% end %>

Relevant routes

 Rails.application.routes.draw do
  resources :languages_users
  devise_for :users, controllers: { registrations: "users/registrations" }
  resources :users
    get 'languages_users/:id/sign_up', to: 'languages_users#sign_up', as: 'sign_up'

 end

I'm still learning - so please let me know if you need to see anything else. Thanks!

Aucun commentaire:

Enregistrer un commentaire