Single Table Inheritance in Rails 4

自闭症网瘾萝莉.ら 提交于 2020-01-15 06:42:18

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/17480029/single-table-inheritance-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!