Reputation: 18871
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
.
Upvotes: 2
Views: 367
Reputation: 44675
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
Upvotes: 2