如何限制on Rails的
问题描述:
使用Ruby的特定属性指定的子类我有一个单表继承层次结构类,如下所示:如何限制on Rails的
# Table name: blocks
#
# video_name :string
# text_name :string
#
class Block < ApplicationRecord
...
end
class VideoBlock < Block
end
class TextBlock < Block
end
的blocks
表保存所有的属性,这些属性Block
子类将使用。
我想说明如何访问:
-
video_name
只有当你正在处理VideoBlock
对象 -
text_name
只有当你正在处理TextBlock
对象
怎么办我在Ruby on Rails中执行此操作? (使用5.x的具体)
答
如果你想在子类墙上的了,你需要决定要如何处理这个问题。你想忽略放在那里的数据,还是想吓坏并着火?
有关着火:
class Video
validates :text_name,
absence: true
end
这将通过提高验证异常隔离开的这一子分类的各种属性。
忽视:
class Video
def text_name=(v)
# Ignored
end
end
这是不太可取的,因为它吃,你可能要实际保存数据,但由于存在错误,正在失去。
答
您可以通过创建自定义getter和setter方法做到这一点:
class MyError < StdError; end
class Block < ApplicationRecord
def video_name
raise MyError unless video?
super
end
def video_name=(value)
raise MyError unless video?
super
end
def video?
self.class.name == 'VideoBlock'
end
end
你'提高'*或*你'返回'。这两个看起来非常非常奇怪。 'raise'将会弹出一个exeption,'return'永远不会运行。 – tadman
好点@tadman – max