0

I'm running into a seemingly simple problem, but I can't figure out what the problem is. I'm building an API using Rails 4.

I have a model called Constant

class Constant < ActiveRecord::Base

  def self.calcuate_something(a, b, c, d, e)
    self.number_one + self.number_two + (self.number_three*a) + (self.number_four*b) + (self.number_five*c) + (self.number_six*d) + (self.number_seven*e)
  end

end

This model has attributes number_one, number_two, number_three, number_four, number_five, number_six, and number_seven.

In my controller, I'm doing this:

@constant = Constant.find_by_id(params[:id])
number = @constant.calculate_something(1, 2, 3, 4, 5)

And then I get an error that says NoMethodError (undefined method 'number_one' for #<Class:0x007fd3d4466068>):. I'm not trying to access a method called number_one, I'm trying to find the field in the model.

I've verified that there is a column called number_one for all of my entries and that every single entry has a value. Is there something wrong with my syntax or setup??

Thanks in advance!

2 Answers 2

2

The issue is with your definition of self.calculate_something(a, b, c, d, e). Using the keyword self is actually creating a class method instead of an instance method, and therefore doesn't have access to those attributes.

Try refactoring it to def calculate_something(a, b, c, d, e)

Update from comments:

The second issues is @constant is being assigned to the ActiveRecord_Relation generated by Constant.find_by_id(params[:id]) instead of the record instance since rails doesn't automatically evaluate queries until necessary. This can be fixed by changing find_by_id to find, or force the query to execute by Constant.find_by_id(params[:id]).first. Personally, I like changing to find as you know the specific record you want.

Sign up to request clarification or add additional context in comments.

2 Comments

But then when I do that, I get a NoMethodError for calculate_something. More specifically, it looks like this NoMethodError (undefined method 'number_one' for #<Constant::ActiveRecord_Relation:0x007fd3d43fec88>):. Why is this happening??
ahh, doing find_by_id is returning a result set, which is the ActiveRecord_Relation part. Change find_by_id to find, or change the statement to Constant.find_by_id(params[:id]).first
1

Read about Class and Instance Methods in Ruby, you want to define method for object as instance method without self.:

def calculate_something(a, b, c, d, e)

But, if you want to define class method, so you need to use self.

Don't use find_by_id, you need to use find as the following:

@constant = Constant.find(params[:id])

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.