2017-10-09 67 views
-1

使用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的具体)

回答

1

如果你想在子类墙上的了,你需要决定要如何处理这个问题。你想忽略放在那里的数据,还是想吓坏并着火?

有关着火:

class Video 
    validates :text_name, 
    absence: true 
end 

这将通过提高验证异常隔离开的这一子分类的各种属性。

忽视:

class Video 
    def text_name=(v) 
    # Ignored 
    end 
end 

这是不太可取的,因为它吃,你可能要实际保存数据,但由于存在错误,正在失去。

1

您可以通过创建自定义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 
+1

你'提高'*或*你'返回'。这两个看起来非常非常奇怪。 'raise'将会弹出一个exeption,'return'永远不会运行。 – tadman

+0

好点@tadman – max