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

Asked

Viewed 262 times

0

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

So: users/_form.html.erb : shall contain a check-box containing the subclasses of Users, And once selected a subclass I can instantiate it or render your form.

Example: the user select Colaborador is rendered Employees/_form.html.erb`.

  Se alguém puder também dar uma dica ou exemplo de como implementar.

3 answers

1

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

What I suggest to you is to implement only one model if Clientemployee and Admin are similar, and differentiate the two through a "type" field in the BD, for example.

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

1


I don’t know if I understand you very well, but I believe this could give you some 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

1

Best solution in my view: Create a single User model and a boolean admin attribute. This way you can make ifs in views:

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

Do not use an attribute called type to differentiate normal users from admins. If you need to use any other name. The attribute name type is reserved in Rails to make Single-Table Inheritance, something that is much more elaborate and complicated than you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.