3

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.

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.