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
然后在控制台中:
>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/ree-1.8.7-2011.03@myapp/gems/activerecord-3.0.7/lib/active_record/associations/association_proxy.rb:216:in `method_missing'
>Post.find(comment.commentable).blah
=> "blah"
为什么这不起作用?
答案 0 :(得分: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
然后,关联代理应该按照您的预期行事。