简体   繁体   中英

Single Table Inheritance in Rails 4

I'm trying to implement a somewhat simple STI in Rails 4, but there's something I can't yet manage to achieve.

I have the following classes:

class Person < ActiveRecord::Base
end

class NaturalPerson < Person
end

class LegalPerson < Person
end

class Employee < NaturalPerson
end

class Customer < NaturalPerson
end

The thing is, I have some attributes that I want to access only from the Employee class, some only from Customer, etc, but I can't find the way. If I were to be using Rails 3's way I would've solved it with attr_accesible. But this isn't posible now, since I'm neither using the attr_accesible gem, nor I'm willing to.

I woud use different person_params in my controller,

def person_params
params.require(:person).permit(:email, :last_name, :first_name)
end

def natural_person_params
params.require(:person).permit(:email, :job, :location)
end

and create a method where I would test the class name of object or the type attribute as it is a STI) to determine which params to use...

Hope this helps

Cheers

If you're trying to use a single controller for all of the models, then put ALL the attributes into the white listed params.

def person_params
  params.require(:person).permit(:email, :last_name, :first_name, :job, :location)
end

If you want to separate them, then you'll want separate params for each type of person:

def person_params
  params.require(:person).permit(:email, :last_name, :first_name)
end

def employed_person_params
  params.require(:person).permit(:email, :job, :location)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM