2

У меня есть модифицированная форма «sign_up» Devise (новая регистрация), которая включает в себя поля для объектов для детей и внуков, которые должны быть созданы вместе с пользователем. Все отношения модели правильно настроены с доступом к атрибутам ребенка. Однако, когда отображается форма, отображаются только поля для пользователя Devise и один из внуков.Devise Registration, не показывающая «некоторые» поля вложенных форм. Rails 4

Когда пользователя создан, он/она будет автоматически назначен клиентами объекта, счетов объекта, и Адреса объекта. Как вы можете видеть по отношениям в модели пользователя ниже, У пользователя есть один Клиент и Клиент имеет много Учетных записей и один Адрес. Ранее возникла проблема с предоставлением формы вообще, которую я решил, изменив значения, переданные методу построения. ПОЧЕМУ НЕ ЭТОТ РАБОТА ??? Это то, что я до сих пор:

* user.rb

class User < ActiveRecord::Base 
    before_create :generate_id 

    # Virtual attribute for authenticating by either username or email 
    # This is in addition to a real persisted field like 'username' 
    attr_accessor :login 

    has_one :customer, :dependent => :destroy 
    has_many :accounts, through: :customer 
    accepts_nested_attributes_for :customer, :allow_destroy => true 
    accepts_nested_attributes_for :accounts, :allow_destroy => true 

    has_one :address, through: :customer 
    accepts_nested_attributes_for :customer, :allow_destroy => true 
    accepts_nested_attributes_for :address, :allow_destroy => true 

    has_one :administrator 

    validates_uniqueness_of :email, :case_sensitive => false 
    validates_uniqueness_of :id 
    validates :username, 
    :presence => true, 
    :uniqueness=> { 
     :case_sensitive => false 
    } 

    # User ID is a generated uuid 
    include ActiveUUID::UUID 
    natural_key :user_id, :remember_created_at 
    belongs_to :user 
    # specify custom UUID namespace for the natural key 
    uuid_namespace "1dd74dd0-d116-11e0-99c7-5ac5d975667e" 

    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :trackable, :validatable 

    # Generate a random uuid for new user id creation 
    def generate_id 
    self.id = SecureRandom.uuid 
    end 

    # Allow signin by either email or username ("lower" function might have to be removed?) 
    def self.find_for_database_authentication(warden_conditions) 
     conditions = warden_conditions.dup 
     if login = conditions.delete(:login) 
     where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first 
     else 
     where(conditions.to_h).first 
     end 
    end 
end 

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController 

    before_filter :configure_permitted_parameters 

    # GET /users/sign_up 
    def new 
    @user = User.new 

    build_resource({}) 
    self.resource[:customer => Customer.new, :account => Account.new, :address => Address.new] 
    respond_with self.resource 
    end 

    def create 
    @user = User.new 
    # Override Devise default behavior and create a customer, account, and address as well 

    resource = build_resource(params[:sign_up]) 

    if(resource.save) 
    sign_in(resource_name, resource) 
    respond_with resource, :location => after_sign_up_path_for(resource) 
    else 
    render :action => "new" 
    end 
    end 

    protected 

    def configure_permitted_parameters 
    devise_parameter_sanitizer.for(:sign_up) { |u| 
     u.permit(:username, :email, :password, :password_confirmation, 
       customer_attributes: [:title, :firstname, :lastname, :phone1, :phone2], 
       account_attributes: [:acct_type], 
       address_attributes: [:address1, :address2, :zip_code]) 
    } 
    end 
end 

application_controller.rb

class ApplicationController < ActionController::Base 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 

    before_filter :configure_permitted_parameters, if: :devise_controller? 

    def after_sign_in_path_for(resource) 
    if current_user.role == 'admin' 
     adminview_administrator_path(current_user, format: :html) 
    else 
     accounts_path(current_user, format: :html) 
    end 
    end 

    protected 
    def configure_permitted_parameters 
     devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, 
              customer_attributes: [:title, :firstname, :lastname, :phone1, :phone2], 
              account_attributes: [:acct_type], 
              address_attributes: [:address1, :address2, :zip_code]) } 
     devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :email, :password) } 
     devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password) } 
    end 
end 

просмотров/изобретает/регистрации/new.html.erb

<h1>Create an account</h1> 
    <div class="panel panel-default" style="width: 50%; padding: 0 25px;"> 

    <%= bootstrap_nested_form_for(resource, as: resource_name, url: user_registration_path(resource_name)) do |f| %> 
     <%= devise_error_messages! %> 
     <h3>User Info</h3> 
     <!-- fields for User object --> 
     <%= f.text_field :username, autofocus: true %> 
     <%= f.email_field :email %> 
     <%= f.password_field :password , autocomplete: "off"%> 
      <% if @validatable %> 
      <em>(<%= @minimum_password_length %> characters minimum)</em> 
      <% end %><br /> 
     <%= f.password_field :password_confirmation, autocomplete: "off" %> 

     <!-- fields for Customer object --> 
     <%= f.fields_for :customer do |customer_fields| %> 
      <%= customer_fields.text_field :title %> 
      <%= customer_fields.text_field :firstname %> 
      <%= customer_fields.text_field :lastname %> 
      <%= customer_fields.text_field :phone1 %> 
      <%= customer_fields.text_field :phone2 %> 
     <% end %> 

     <!-- fields for Account object --> 
     <%= f.fields_for :account do |account_fields| %> 
      <%= account_fields.text_field :acct_type %> 
     <% end %> 

     <!-- fields for Address object --> 
     <%= f.fields_for :address do |address_fields| %> 
      <%= address_fields.text_field :address1 %> 
      <%= address_fields.text_field :address2 %> 
      <%= address_fields.text_field :zip_code %> 
     <% end %> 
     <br /> 
     <div class="actions"> 
     <%= f.submit "Create My Account", :class => "btn btn-info" %> 
     </div> 
     <% end %> 
    </div> 
</div> 

Опять же, выше вид делает рендер, но форма отображает только поля для DEViSE нового пользователя и один полевого (acct_type) для учетной записи поля. Как получить остальную форму для отображения и создания всех этих вещей при подаче? Все, что я пробовал, и все, что я прочитал, заставляет меня думать, что есть проблема с сильными параметрами Rails 4, которые не могут распознать разрешенные атрибуты (см. Выше контроллеры) в массиве. Это может быть проблема? Если да, то как идти о передаче параметров, необходимых для создания всех этих вещей?

Может быть проблема с маршрутами? routes.rb

Rails.application.routes.draw do 
    devise_for :users, :controllers => { :registrations => "registrations" } 

    devise_scope :user do 
    # authentication 
    post "/accounts/adminview" => "devise/sessions#new" 
    end 

    root 'home#index' 

    resources :administrators do 
    member do 
     get :adminview 
    end 
    end 

    resources :users do 
    resource :customers 
    resource :accounts 
    resource :addresses 
    end 

    resources :account_types, :accounts, :addresses, :administrators, :customers, :transaction_types, :transactions, :users 

end 

Я пробовал все комбинации способов, которые я мог бы найти на SO. Это заняло ценное время. Я не вижу причин, почему он не может работать. У кого-нибудь есть лучший способ сделать это? Есть ли камень, который поможет? Я готов разорвать Разделение и при необходимости восстановить.

F.Y.I. Это Rails 4 и Devise 3.4.1. Я также добавил nested_form gem, но это не имеет значения.

Спасибо

+0

По-видимому, невозможно создать глубоко вложенные модели внутри формы входа в Devise. Это глупо. –

+0

Вы выяснили, как заставить это работать? – Mel

ответ

0

Если вы поднимаете Params в контроллере вы, вероятно, видите accounts_attributes вместо account_attributes вы устанавливаете в разрешении на application_controller, попробуйте заменить его.

 Смежные вопросы

  • Нет связанных вопросов^_^