1

Fairly new to RoR and wondering how I might move this one line of code out of my view and into my controller. I am also using devise and a current user is logged in. Thanks in advance

profile.html.erb

 <%= @profile.calorie / 4  %>

Ive set up a method called calculate within my profiles_controller.rb like so

 helper_method :calculate

 def calculate 
  ..... 
 end 
4
  • what does this calculation represents? Commented Feb 10, 2014 at 20:07
  • 1
    Personally I wouldn't care for such a simple calculation in a view, unless you are using it in more than one place. Creating helper for this seems like an overkill. Commented Feb 10, 2014 at 20:11
  • So how might I translate that in a controller without a helper method? Commented Feb 10, 2014 at 20:15
  • @ssosina - Don't. It is fine to keep little calculations like that in a view. It is much better than creating new instance variable or method. Commented Feb 10, 2014 at 20:37

1 Answer 1

1

Just put the calculation in an instance variable in your controller and call it in your view:

<%= @new_calorie  %>

And in your controller action:

def show #or index
   @new_calorie = @profile.calorie / 4
end
Sign up to request clarification or add additional context in comments.

2 Comments

It's because you haven't chosen a record of the object yet. If you just call Profile you're only calling the class, and not any individual records. You'll have to do something like Profile.find(id: params[:id]).calorie / 4 in order to find the calorie of a particular Profile record.
Did @calorie = current_user.profile.calorie as i'm using devise. This worked. Thanks for your help

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.