Rails 4 中的单表继承 [英] Single Table Inheritance in Rails 4

查看:48
本文介绍了Rails 4 中的单表继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Rails 4 中实现一个稍微简单的 STI,但有些东西我还无法实现.

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

我有以下课程:

class Person < ActiveRecord::Base
end

class NaturalPerson < Person
end

class LegalPerson < Person
end

class Employee < NaturalPerson
end

class Customer < NaturalPerson
end

问题是,我有一些我只想从 Employee 类访问的属性,一些只能从 Customer 类访问,但我找不到方法.如果我使用 Rails 3 的方式,我会用 attr_accesible 解决它.但这现在不可能了,因为我既不使用 attr_accesible gem,也不愿意使用.

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.

推荐答案

我会在控制器中使用不同的 person_params,

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

并创建一个方法,我将在其中测试对象的类名或类型属性,因为它是 STI)以确定要使用哪些参数...

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...

希望能帮到你

干杯

这篇关于Rails 4 中的单表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆