简体   繁体   English

Noob问题:Ruby on Rails中的类和实例方法

[英]Noob question: Class and instance methods in Ruby on Rails

I have a function called update_status inside my comments_controller.rb: 我在comments_controller.rb中有一个名为update_status的函数:

def update_status
  @comment.relative_value = @comment.points_up - @comment.points_down
  randomize!
end

Where @comment = Comment.find(params[:id]) 其中@comment = Comment.find(params[:id])

Because of the way I've set up the website, I want to be able to call c.update_status for any comment c. 由于我设置网站的方式,我希望能够为任何评论c调用c.update_status。 For example, in my posts_controller, I want to be able to do this: 例如,在我的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

How do I get this to work? 我如何让它工作? I keep getting undefined method error for # < Comment > . 我一直为# < Comment >获取未定义的方法错误。 Do I have to do def self.update_status ? 我必须做def self.update_status吗? That didn't seem to work either. 这似乎也没有用。

You're confusing a helper function update_status() in your controller with a member function on the comment instance. 您在控制器中使用注释实例上的成员函数来混淆辅助函数update_status()。 You can make your controller code work by passing the comment to the helper function as an argument: 您可以通过将注释作为参数传递给辅助函数来使控制器代码工作:

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

You could also add this as a member function on the Comment class itself, like this: 您还可以将此作为成员函数添加到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM