About Me

My photo
जिंदगी की परीक्षा में कोई नम्बर नहीं मिलते है लोग आपको दिल से याद करे तो समझ लेना आप पास हो गए....

Wednesday 7 June 2017

How to add nested form in devise resource


How to add nested form in devise resource


Problem: Suppose We have a User has one Company model relationship (where company has name attribute) and while signup you want to add and validate company name (uniqueness).

Solution:

1.add following lines in User model

accepts_nested_attributes_for :company
validates_associated :company

2. To override devise views

rails g devise:views users 

3. Modify the app/views/devise/registrations/new.html.haml

  = form_for(resource, as: resource_name, url: registration_path(resource_name), class: "form-signin") do |f|
    %h4.form-signin-heading
      = "Sign up"
    = devise_error_messages!
    .field
      = f.email_field :email, autofocus: true, class: 'form-control', placeholder: "Email"
    = f.fields_for :company do |a|
      .field
        = a.text_field :name,  class: 'form-control', placeholder: "Company Name"
    .field
      = f.password_field :password, autocomplete: "off", class: 'form-control', placeholder: "Password"
    .field
      = f.password_field :password_confirmation, autocomplete: "off", class: 'form-control', placeholder: "Confirm Password"
    %br/
    %button.btn.btn-lg.btn-primary.btn-block{:type => "submit"} Sign Up
  = render "devise/shared/links"

5.   In Application Controller override devise's  configure_permitted_parameters method

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [company_attributes: :name] )
end

6.Override Registration controller (generate Registration controller inside user folder) and copies the following co

class Users::RegistrationsController < Devise::RegistrationsController

  def new
    build_resource({})
    resource.build_company
    respond_with self.resource
  end
end

Please let me know if any issue or correction in my post.

No comments:

Post a Comment