How should I use the alias_method_chain for the build method?

末鹿安然 提交于 2019-12-14 03:56:56

问题


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>'

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)?


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).

Note II: The same error occurs when considering the new method instead of build; that is, when using alias_method_chain :new, :option_name.


回答1:


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


来源:https://stackoverflow.com/questions/18163004/how-should-i-use-the-alias-method-chain-for-the-build-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!