问题描述
我使用on Rails的Ruby的3.2.13,我想正确使用 alias_method_chain:构建,:OPTION_NAME
语句,因为我得到一个奇怪的错误。即,...
I am using Ruby on Rails 3.2.13 and I would like to properly use the alias_method_chain :build, :option_name
statement since I am getting a strange error. That is, ...
......我的控制器文件我有:
... in my controller file I have:
class Articles::CommentsController < ApplicationController
def create
@articles_comment = @article.comments.build(params[:comment])
...
end
end
......在我的模型文件我有:
... in my model file I have:
class Articles::Comment < ActiveRecord::Base
def self.build_with_option_name
...
end
alias_method_chain :build, :option_name
end
当我运行创建
控制器操作,我得到的日志出现以下错误:
When I run the create
controller action I get the following error in log:
ActionController::RoutingError (undefined method `build' for class `Articles::Comment'):
app/models/articles/comment.rb:5:in `<class:Comment>'
的我应该如何使用 alias_method_chain
为建立
方法?的或者,也许好,我应该继续以另一种方式达到我想什么做(例如,我应该覆盖建立
方法在文章::注释
模式,而不是使用 alias_method_chain
)?
How should I use the alias_method_chain
for the build
method? Or, maybe better, should I proceed in another way to reach what I would like to make (for example, should I overwrite the build
method in the Articles::Comment
model instead of using alias_method_chain
)?
的注意I 的:我不知道是否有帮助,但建立
法是指联想( @ article.comments
)。更多的,我不说出建立
方法在文章::评论
模型,因为它应该是加/在Ruby on Rails框架本身(我认为这是通过元编程制作)附加的类。
Note I: I don't know if it helps, but the build
method refers to an association (@article.comments
). More, I do not state the build
method in the Articles::Comment
model because it should be "added" / "attached" to the class by the Ruby on Rails framework itself (I think it is made through meta-programming).
的注二的:考虑到新
方法,而不是建时发生同样的错误
;也就是说,当使用 alias_method_chain:新:OPTION_NAME
Note II: The same error occurs when considering the new
method instead of build
; that is, when using alias_method_chain :new, :option_name
.
推荐答案
正如你所说的,是建立在联想代理定义的方法。你可以做的就是用联想扩展,因此模型中可以传递块到你的has_many调用,将被视为给定association_proxy延期:
As you said, build is a method defined on association proxy. What you can do is to use association extensions, so in a model you can pass a block to your has_many call, which will be treated as an extension for given association_proxy:
class Article < ActiveRecord::Base
...
has_many :comments do
alias_method_chain :build, :option_name
end
这篇关于我应该如何使用的构建方法alias_method_chain?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!