Jon
Jon

Reputation: 129

Noob question: Class and instance methods in Ruby on Rails

I have a function called update_status inside my comments_controller.rb:

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

Where @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. For example, in my posts_controller, I want to be able to do this:

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 >. Do I have to do def self.update_status? That didn't seem to work either.

Upvotes: 3

Views: 135

Answers (1)

Winfield
Winfield

Reputation: 19145

You're confusing a helper function update_status() in your controller with a member function on the comment instance. 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:

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

Upvotes: 6

Related Questions