2013-07-17 1 views
1

Я относительно новичок в рельсах и пытаюсь настроить несколько типов пользователей с помощью Devise (заемщиков и кредиторов). Я следовал этому руководству Multiple user models with Ruby On Rails and devise to have separate registration routes but one common login routeРазработка нескольких пользователей - неинициализированная константа UserRegistrationsController

но продолжал придумывать ошибку «неинициализированный постоянный UserRegistrationsController».

вот код, который я обновил из основного завещанию и местоположения (некоторые из них я переехал/созданный на основе моего понимания учебника, но те, может быть неправильно):

В: приложение/контроллеры/пользователи/registrations_controller.rb

class UserRegistrationsController < Devise::RegistrationsController 
def create 
build_resource 

# customized code begin 

# crate a new child instance depending on the given user type 
user_type = params[:user][:user_type] 
resource.rolable = child_class.new(params[child_class.to_s.underscore.to_sym]) 

# first check if child instance is valid 
# cause if so and the parent instance is valid as well 
# it's all being saved at once 
valid = resource.valid? 
valid = resource.rolable.valid? && valid 

# customized code end 

if valid && resource.save # customized code 
    if resource.active_for_authentication? 
    set_flash_message :notice, :signed_up if is_navigational_format? 
    sign_in(resource_name, resource) 
    respond_with resource, :location => redirect_location(resource_name, resource) 
    else 
    set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource)  if is_navigational_format? 
    expire_session_data_after_sign_in! 
    respond_with resource, :location => after_inactive_sign_up_path_for(resource) 
    end 
else 
    clean_up_passwords(resource) 
    respond_with_navigational(resource) { render :new } 
    end 
end 
end 

в: приложение/контроллеры/users_controller.rb

class UsersController < ApplicationController 
def show 
@user = User.find(params[:id]) 
@pins = @user.pins.page(params[:page]).per_page(20) 
end 
end 

в: приложение/модели/borrower.rb

class Borrower < ActiveRecord::Base 
has_one :user, :as => :rolable 

has_many :pins 
end 

В: приложение/модели/lender.rb

class Lender < ActiveRecord::Base 
has_one :user, :as => :rolable 

has_many :pins 
end 

В: приложение/модели/user.rb

class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :token_authenticatable, :confirmable, 
# :lockable, :timeoutable and :omniauthable 
devise :database_authenticatable, :registerable, 
     :rememberable, :trackable, :validatable #:recoverable, 

# Setup accessible (or protected) attributes for your model 
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :description 
# attr_accessible :title, :body 

belongs_to :rolable, :polymorphic => true 

has_many :pins 

end 

В: приложение/просмотров/DEViSE/user_registrations/_borrower_fields. HTML

<div><%= f.label :label_name %><br /> 
<%= f.text_field :label_name %></div> 

В: приложение/просмотров/Завещание/user_registrations/_lender_fields.html

<div><%= f.label :label_name %><br /> 
<%= f.text_field :label_name %></div> 

В: приложение/просмотров/изобрести/user_registrations/new.html.erb

<h2>Sign up</h2> 

<% 
# customized code begin 

params[:user][:user_type] ||= 'borrower' 

if ["borrower", "lender"].include? params[:user][:user_type].downcase 
child_class_name = params[:user][:user_type].downcase.camelize 
user_type = params[:user][:user_type].downcase 
else 
child_class_name = "Borrower" 
user_type = "borrower" 
end 

resource.rolable = child_class_name.constantize.new if resource.rolable.nil? 

# customized code end 
%> 

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: {class: 'form-horizontal'}) do |f| %> 
<%= f.error_notification %> 

<%= f.input :name %> 
<%= f.input :email %> 
<%= f.input :password %> 
<%= f.input :password_confirmation %> 
<%= f.input :description, label: "Tell Us About Yourself" %> 

<% # customized code begin %> 
<%= fields_for resource.rolable do |rf| %> 
<% render :partial => "#{child_class_name.underscore}_fields", :locals => { :f => rf } %> 
<% end %> 

<%= hidden_field :user, :user_type, :value => user_type %> 
<% # customized code end %> 

<div class="form-actions"> 
<%= f.submit "Sign up", class: "btn btn-primary" %> 
</div> 
<% end %> 

<%= render "devise/shared/links" %> 

В: конфигурации/локалей/routes.rb:

get "users/show" 

resources :pins 

devise_for :users, :controllers => { :registrations => 'UserRegistrations' } 
match 'users/:id' => 'users#show', :as => :user 

get 'about' => 'pages#about' 
get 'clothing' => 'pages#clothing' 
get 'bags' => 'pages#bags' 
get 'shoes' => 'pages#shoes' 
get 'stylefeed' => 'pages#stylefeed' 
get 'accessories' => 'pages#accessories' 
get 'designers' => 'pages#designers' 

root :to => 'pins#index' 

match 'borrower/sign_up' => 'user_registrations#new', :user => { :user_type => 'borrower' } 
match 'lender/sign_up' => 'user_registrations#new', :user => { :user_type => 'lender' } 

Я также добавил Rolabe ID и Rolable Type для таблицы пользователей и сформировал контроллер регистрации.

Есть ли у кого-нибудь идеи относительно того, где я ошибаюсь? Спасибо!

ответ

1

Rails autoload не находит файл для класса. Переименовать UserRegistrationsController на Users::RegistrationsController

+0

И если я могу сказать слово с точки зрения дизайна - кредитор и заемщик - это не то, что вырезано из камня, поэтому вы, вероятно, предпочли бы иметь одну модель пользователя и ассоциировать профили (кредитор и заемщик) контекст. –

+0

, похоже, не работал для меня. Любые другие мысли? –

+0

Что значит «не казалось». Rails дает ошибки, ошибки имеют объяснение и обратную трассировку. –