开发者

What is the best way to have a multiple model based form for account creation in Devise (RoR)

开发者 https://www.devze.com 2023-02-18 19:24 出处:网络
EDIT NOTE I am rewording this question entirely now that I have a bit better understanding of rails & devise.

EDIT NOTE I am rewording this question entirely now that I have a bit better understanding of rails & devise.

I am looking for a way to utilize a single table structure (Account) to create various account types.

What I am now having a hard time with is a structure where I need my Business to have an account but not necessarily vice versa (an Account could just be a typical u开发者_如何学Cser). I think the easiest approach would be just to have a 1 to 1 relation as opposed to inheritance but I could be mistaken there.

The reason its confusing to me is the registration process. If I accept the account information, I believe I could use accepts_nested_attributes_for to accept the account information but im afraid that'll break the workflow that devise is expecting. I considered overriding Devise::RegistrationController but I don't really know how rails is going to handle that (ie, if I call super but I am dealing with a Business rather than an Account - what happens?)


You can use CanCan to make account roles, and ask in your code current_user.role?(:admin)

There is good app template with device/cancan/spike integrated:

https://github.com/augusto/devise-cancan-spike


There is no problem per-se with having a form which manages multiple models, so long as the models are related to one another.

The 'stock' way of achieving this would be to use 'accepts_nested_attributes_for' in your model.

For your situation, you'd do something like this:

class Employee < ActiveRecord::Base
  belongs_to :business
  accepts_nested_attributes_for :business
end

Then in your registration view, you would use:

<!-- validation errors etc -->
<%= form_for @employee do |f| %>
  <!-- all your employee fields etc -->

  <%= f.fields_for :business do |b| %>
    <p>
      <%= b.label :name %>
      <br/>
      <%= b.text_field :name %>
    </p>

    <!-- more fields from business -->
  <% end %>
<% end %>

If you wanted to handle both employee and 'normal user' registration in the same form, you could probably do something like this (never tried this, but I think it should work!):

<!-- validation errors etc -->
<%= form_for @person do |f| %>
  <!-- all your person fields etc, assuming no extras for employee -->

  <% if @person.respond_to? :business %>
    <%= f.fields_for :business do |b| %>
      <p>
        <%= b.label :name %>
        <br/>
        <%= b.text_field :name %>
      </p>

      <!-- more fields from business -->
    <% end %>
  <% end %>
<% end %>

P.S. you mentioned in your question that you were worried Devise wouldn't cope with nested attributes. It definitely does, as I do exactly this in one of my applications.

0

精彩评论

暂无评论...
验证码 换一张
取 消