Reputation: 259
I have two tables: User
, table1
and table2
. User has_many table1
. User has_many table2
. table2
has 3 columns: column1
, column2
, column3
. What I want to do is to multiply the value in column1
and column2
by a number and save it to column3
.
In my table2.rb
class file, I have defined this method:
def calculate(tablerow)
tablerow.column3 = (tablerow.column1 * 1) + (tablerow.column2 * 2)
end
I have a method in table1Controller
, which has a method do something. This method then calls the table2#calculate
method above and passes an appropriate parameter.
When I call the calculate
method, I get the following error message:
NoMethodError in table1Controller#dosomething
undefined method `*' for nil:NilClass
Now I know there is something not right about the calculate
method. But I am not sure how to achieve what I am trying to achieve, which is just to do a calculation on the value of 2 columns and save the sum to a third column. My app uses SQLite3.
Upvotes: 0
Views: 275
Reputation: 2736
undefined method * for nil:NilClass
means that one of the values you are trying to multiply is empty. In your example tablerow.column3
is probably nil. I think you either have a typo in your code or gave the example code wrong because the code does not match what you say you are trying to achieve.
Give this a shot, it should also eliminate the need to call this action from your controller and just save the value of column3 each time you save or create a record in table2
class Table2 < ActiveRecord::Base
before_save :calculate_column3
def calculate_column3
self.column3 = (self.column1 * 1) + (self.column2 * 2)
end
end
Upvotes: 2