How to instantiate a model and get its resources by its name in Ruby on Rails

0

Since I have the abstract class User , and its subclasses Client Employee and Admin , I would like to render screens according to the chosen subclass.

Therefore:      users/_form.html.erb : should contain a selection box with the subclasses of Users , and as soon as a subclass is selected I can instantiate it or render its form.

  

Example: When user select Colaborador is rendered   employees / _form.html.erb '.

  Se alguém puder também dar uma dica ou exemplo de como implementar.
    
asked by anonymous 12.01.2015 / 14:29

3 answers

1

I do not know if I understand very well, but I believe this can give you insight.

# app/controlles/users_controller.rb
class UsersController < ApplicationController
  def edit
    @user = User.find(params[:id])

    if @user.is_a?(Employee)
      render 'employees/edit'
    end

    # Se preferir podes fazer algo dinâmico.
  end
    
12.01.2015 / 22:13
1

There is no abstract class in Ruby, and I believe you will not have gained in implementing this.

What I suggest is to implement just a case model ClientEmployee and Admin are similar, and differentiate the two through a field "type" in the DB, for example.

The other suggestion, if they are quite different is to create a User model with the code and fields in common and two ClientEmployee and Admin models inheriting from it. So you would create a controller for each ...

    
06.03.2015 / 01:11
1

Best solution in my vision: Create a User-only model and an Boolean admin attribute. This way you can do ifs in the views:

<% if @user.admin? %>
   ...
<% end %>

Do not use an attribute called type to differentiate normal users from admins. If necessary, use any other name. The type attribute name is reserved in rails to do #, something that is much more elaborate and complicated than you need.

    
22.03.2015 / 21:38