My app is supposed to allow users to create a status_update, that draws info from a previous status_update through a method called ‘previous_status_update”.
Within my view I have this code:
<span> <%= status_update.current_weight - status_update.previous_status_update.current_weight %></span>
Within my model I have this corresponding code:
after_find :previous_status_update
def previous_status_update
current_id = self.id
previous_status_update = user.status_update.where( "created_at < ? ", self.created_at ).first
end
within the console the following commands, in order, work perfectly:
user = User.find_by_id(3)
#<User id: 3, email: "example-3@r
status = user.status_update.first
#<StatusUpdate id: 73, created_at: "2012-09-13 23:08:35",......
status.previous_status_update
#<StatusUpdate id: 68, created_at: "2012-09-13 23:08:35".....
prev_stat = status.previous_status_update
prev_stat.current_weight
=> 168
I’m guessing the problem is that the model isn’t placing the active record object into an instance variable that can be called upon like an object. Instead I simply have a method call that returns the active record object but isn’t in a form that can be called for attributes.
I don’t think I can store the entire object in a database column called “previous_status_update”…
I think that another possibility for this error is that it is pointing to the first entry in the sample data which does not have a previous status update. So when the program tries to come up with a value it simply returns nil. I think this is what the error is referring to.
So really, what I need is for rails to chill out with that exception.
The way I solved this was by returning the first status update it’s self for the non existing ‘previous’ status update.
This fixed the issue.
Here is what the method looks like: