[英]Noob question: Class and instance methods in Ruby on Rails
我在comments_controller.rb中有一个名为update_status的函数:
def update_status
@comment.relative_value = @comment.points_up - @comment.points_down
randomize!
end
其中@comment = Comment.find(params[:id])
由于我设置网站的方式,我希望能够为任何评论c调用c.update_status。 例如,在我的posts_controller中,我希望能够这样做:
def show
@posts = Post.order('trending_value DESC').page(params[:page]).per(5)
@post = Post.find(params[:id])
@comments = @post.comments
@comments.each do |c| #TODO: FIX
c.update_status
c.save
end
end
我如何让它工作? 我一直为# < Comment >
获取未定义的方法错误。 我必须做def self.update_status
吗? 这似乎也没有用。
您在控制器中使用注释实例上的成员函数来混淆辅助函数update_status()。 您可以通过将注释作为参数传递给辅助函数来使控制器代码工作:
def update_status(comment)
comment.relative_value = comment.points_up - comment.points_down
comment.save
randomize!
end
def show
@posts = Post.order('trending_value DESC').page(params[:page]).per(5)
@post = Post.find(params[:id])
@comments = @post.comments
@comments.each do {|c| update_status(c) }
end
您还可以将此作为成员函数添加到Comment类本身,如下所示:
class Comment < ActiveRecord::Base
def update_status
update_attributes(:relative_value => points_up - points_down)
randomize!
end
end
def show
@posts = Post.order('trending_value DESC').page(params[:page]).per(5)
@post = Post.find(params[:id])
@comments = @post.comments
@comments.each do {|c| c.update_status }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.