Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何让gem控制器处理多个任意模型?_Ruby_Ruby On Rails 3_Metaprogramming_Gem - Fatal编程技术网

Ruby 如何让gem控制器处理多个任意模型?

Ruby 如何让gem控制器处理多个任意模型?,ruby,ruby-on-rails-3,metaprogramming,gem,Ruby,Ruby On Rails 3,Metaprogramming,Gem,我有四个模型,我允许四个独立的注释控制器对其进行注释。这四个注释控制器的作用基本相同,只是略有不同 为了消除四个基本相同的注释控制器的重复,我创建了一个Rails引擎作为gem,可以任意处理我在routes.rb中指定的任意模型上的注释 因此,在我的routes.rb文件中,我现在可以使用: comments_on :articles, :by => :users 在我的创业板中,我对以下内容进行了评论: def comments_on(*resources) options = r

我有四个模型,我允许四个独立的注释控制器对其进行注释。这四个注释控制器的作用基本相同,只是略有不同

为了消除四个基本相同的注释控制器的重复,我创建了一个Rails引擎作为gem,可以任意处理我在routes.rb中指定的任意模型上的注释

因此,在我的routes.rb文件中,我现在可以使用:

comments_on :articles, :by => :users
在我的创业板中,我对以下内容进行了评论:

def comments_on(*resources)
  options = resources.extract_options!

  [snip of some validation code]

  topic_model = resources.first.to_s
  user_model = options[:by].to_s

  # Insert a nested route
  Rails.application.routes.draw do
    resources topic_model do
      resources "comments"
    end
  end
end
路由显示在“rake routes”中,请求被正确地路由到我的gem的“commentscoontroller”,但这就是我的gem功能结束的地方

在我的gem CommentsController中检测上下文以便处理特定于如何调用comments_的请求的最佳方法是什么

更具体地说,我将如何实现如下索引操作,使其具有上下文感知能力

def index
  @article = Article.find(params[:article_id])
  @comments = ArticleComment.find(:all, :conditions => { :article_id => @article.id })
end

谢谢你的帮助

您可以将主题指定为路由中的额外参数:

Rails.application.routes.draw do
  resources topic_model do
    resources "comments", :topic_model => topic_model.to_s
  end
end
然后您的控制器可以这样写:

def index
  @topic = topic
  @comments = topic.comments
end

protected
def topic
  m = params[:topic_model]
  Kernel.const_get(m).find(params["#{m.underscore}_id"])
end
您可以将大量逻辑移出控制器,也可以移入模型<代码>主题。注释可以是所有这些模型都应该实现的命名范围

我在过去也做过类似的模式,通常有一个边缘案例打破了这个想法,你最终做了比明智的更多的“元”编程

我建议创建一个基本控制器,然后创建从中继承的简单控制器,或者尝试将这些常见行为拆分为模块