2011-12-13 48 views
1
class Post < ActiveRecord::Base 
    post.has_many :comments, :as => :commentable 

    def method_missing(name, *args, &block) 
    puts "blah!" 
    end 
end 

class Comment < ActiveRecord::Base 

    belongs_to :commentable, :polymorphic => true 

end 

然後在控制檯:method_missing在多態關聯中使用時不起作用?

>comment.commentable 
=> #<Post id: 1022, title: "something"> 

>comment.commentable.class 
=> Post(id: integer, title: string) 

>comment.commentable.blah 
NoMethodError: undefined method `blah' for "#<Post:0x10f1e9e10>":Post 
from /Users/patrick/.rvm/gems/[email protected]/gems/activerecord-3.0.7/lib/active_record/associations/association_proxy.rb:216:in `method_missing' 

>Post.find(comment.commentable).blah 
=> "blah" 

爲什麼這個不行?

+1

嗯,在我的作品爲3.1。我的第一個假設是代理類的問題。 –

回答

0

我認爲你需要在你的類定義respond_to?:然後

class Post < AR::Base 

    def method_missing(name, *args, &block) 
    return puts "blah" if name.to_s == 'blah' 
    super 
    end 

    def respond_to?(method_name, include_private = false) 
    super || method_name.to_s == 'blah' 
    end 
end 

協會代理應作爲你所期望的。