I'm trying to implement a somewhat simple STI in Rails 4, but there's something I can't yet manage to achieve.
我试图在Rails 4中实现一个有点简单的STI,但是有些东西我还没做到。
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.
问题是,我有一些只能从Employee类访问的属性,有些只能从Customer类访问,等等,但是我找不到方法。如果我使用Rails 3的方式,我将用attr_accesible解决它。但这并不是肯定的,因为我既没有使用诱人的宝石,也不愿意使用。
2 个解决方案
#1
4
I woud use different person_params in my controller,
我需要在我的控制器中使用不同的person_params,
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...
并创建一个方法,在其中我将测试对象的类名或类型属性,因为它是一个STI),以确定使用哪个params…
Hope this helps
希望这有助于
Cheers
干杯
#2
3
If you're trying to use a single controller for all of the models, then put ALL the attributes into the white listed params.
如果您试图为所有模型使用一个控制器,那么将所有属性放入白色列表的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
#1
4
I woud use different person_params in my controller,
我需要在我的控制器中使用不同的person_params,
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...
并创建一个方法,在其中我将测试对象的类名或类型属性,因为它是一个STI),以确定使用哪个params…
Hope this helps
希望这有助于
Cheers
干杯
#2
3
If you're trying to use a single controller for all of the models, then put ALL the attributes into the white listed params.
如果您试图为所有模型使用一个控制器,那么将所有属性放入白色列表的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