Andrew Cetinic
Andrew Cetinic

Reputation: 2835

Create as a polymorphic type in Rails

I wish to create a polymorphic class (User) as a particular type and use it later with conditions depending on the type of object.

class SuperUser < User
class Admin < User
class User

@user = @account.users.new(params[:user])

This will create a user as a User object. Only way I can think of creating and using @user as a particular type of object is by doing something like this:

@user = Admin.new(params[:user]) if params[:user][:type] == "Admin"
@user = SuperUser.new(params[:user]) if params[:user][:type] == "SuperUser"
@user.account = @account

if @user.is_a? Admin 
 ...
end

....

So, is there a better way to do this?

Upvotes: 2

Views: 641

Answers (2)

AMIT
AMIT

Reputation: 549

Looking at your code, I'm making one assumption. The params[:user][:type] is same as the class name. If thats the case the following code should work.

if params[:user][:type]
  @user = (params[:user][:type]).constantize.new(params[:user])
  @user.account = @account
else
  @user = @account.users.new(params[:user]
end

Upvotes: 0

mikdiet
mikdiet

Reputation: 10018

You can define polymorphic_new class method for User

class User
  def self.polymorphic_new(params)
    case params[:type]
    when "Admin" then Admin.new(params)
    when "SuperUser" then SuperUser.new(params)
    else new(params)
  end
end 

And then in controller

@user = User.polymorphic_new(params[:user])

I'm not concerned the security question though..

Upvotes: 2

Related Questions