2016-12-02 28 views
0

這就提出了一個錯誤「未定義的方法喜」:如何Rails是處理繼承的概念,家長訪問子女

class A 
    def bla 
    hi 
    end 
end 

class B < A 
    def hi 
    puts "Hii" 
    end 
end 

a = A.new 
a.bla 

我有一個Rails應用程序,這是否:

class BlaParentController < ApplicationController 
    before_filter :setting 

    def create 
    @random_obj = ParentRandom.create(permitted_params) 
    end 
end 

class BlaController < BlaParentController 
    private 

    def setting 
    end 

    def permitted_params 
    end 
end 

一個方法調用BlaController#create轉到BlaParentController#create。但BlaParentController正在從其子BlaController訪問方法permitted_paramssetting。這怎麼可能?

+0

你的第二個例子沒有意義。什麼是「ParentRandom」?如果你有直觀的類作爲例子,它也會更容易。 '動物','狗','GermanShepherd',這是清楚如何繼承的作品。 – Amadan

+0

對不起,它必須是這種方式......但你可以使用子類的方法'允許的參數和設置'來獲得父類的想法 – gates

回答

0

對於普通方法,重要的是它是否爲接收器定義。其他類型的上下文(例如,從哪個方法調用)無關緊要。 (少數例外是像Kernel#__dir__Module#nestingException#backtrace方法。)

在第一示例中,接收器是A一個實例,但不是B。因此它可以訪問A中的方法,但不能訪問B中的方法。

在第二個例子中,接收者是BlaController的一個實例,它是BlaParentController的一個子類。因此它可以訪問BlaController中的方法以及BlaParentController中的方法。