matt bin Mon Apr 25 10:21:47 -0400 2011

Subject: Find_by_id()

Hi there im tryng to do something like this:
inside my model:
public function update_news($id,$post) {
$news=Frontend_news::find_by_id($id);//non existent ID
if (empty($news)) {
$news->errors->add('ID','Not found');
return $news;
}
}

The problem is that if I try to find_by_id with a non existent id or a record that does not exist inside my table
it does not create the $news object.
So I cant use $news->errors->add cause there is a non existent object.
In other words how would I check to see if the ID exists and send the error message back to my controller.
using the >errors>add of activerecord.

How would I resolve this problem and am I doing it correctly??
Tnx.


Björn Ali Göransson Mon Apr 25 12:56:49 -0400 2011

Hi,

To what model are you adding this function? It seems a bit out of place!

Shouldn't that logic be right in the controller instead? Or perhaps before you call this method, do the following in the controller: find the News (by ID) and if it doesn't exist, throw an error - otherwise proceed with calling methods on the Model.

Björn Ali

matt bin Mon Apr 25 13:21:24 -0400 2011

Thank you for responding Bjorn
That model is an active record model for my frontend_news table
the table is made up like this:
id,author,title,message,time_created,time_modified

As a matter of fact I can put that logic inside the controller, but according to me it shouldnt be there...
Inside my Activerecord model after I added all the standard validators I created a function whose name is update_news and create_news and delete_news
I would like to call these three functions around in my controllers eventually.
and I don't think checking for the ID should be done in the controller but in this case wihin the update function.
all the controller should know according to me is what model function to call and what parametres to put and in the end check if the model returned the desired result.
and in this case I wanted to call the $news->errors->add() function inside my update_news function inside my active record model, now you can do that if you call the:
$news=Frontend_news::find_by_id($id);
the problem is it won't work if it does not find the id cause the object $news will be empty
I'm using codeigniter.
tnx.

Chris R Wed Apr 27 13:31:56 -0400 2011

I'm with Bjorn - this logic does not belong in your model.

Your controller should attempt to find the record and set the attributes on the model object before calling save(). For example: http://pastie.org/1840067

matt bin Wed Apr 27 14:04:23 -0400 2011

Bjorn And Chris R thank you very much for your solutions.
I will implement it the way you suggest me to:)

(1-4/4)