Rick P Wed Sep 08 09:56:51 -0400 2010

Subject: create/add functions

There just doesn't seem to be much documentation on how to go about creating records in various situations. For example, I have a many to many relationship between 'file' and 'track' through 'track_files' but, as I said, it's not clear how to go about working with this scenario in regards to the C aspect of CRUD.


Kien La Mon Sep 13 20:06:05 -0400 2010

You can use the build and create methods to create associated records. For example:

class Venue extends ActiveRecord\Model {
  static $has_many = array(
    array('events'));
}

class Event extends ActiveRecord\Model {
  static $belongs_to = array(
    array('venue'));
}

$venue = Venue::first();

# creates and saves the model
$venue->create_events(array('description' => 'some event', 'foo' => 'bar'));

# creates the model but does not save to the db
$venue->build_events(array('description' => 'some other event', 'foo' => 'bar'));

I'll write up something more detailed in the wiki soon and post a link to it when it's ready.

Horacio Peña Mon Sep 20 02:51:03 -0400 2010

Seems like we can create new records and relate them, but we can't relate already existing records (at least not in a fancy way).

What we are looking for is something like:

// #1
$user = User::find_by_first_name('john');
$role = Role::find_by_role('admin');

// #2
$user->roles[] = $role;
$user->save();

Or something like that. Another option after #2:

$user->link($role);

If something like this is possible I'm sorry but I couldn't find it in the docs nor the forum.

Ash McKenzie Tue Nov 09 21:24:17 -0500 2010

I too was looking for something like this, what's the generally accepted way of associating existing models to each other ? This is what I'm currently using: -

class User extends ActiveRecord\Model {
static $has_one = array(
array('role'));
}

class Role extends ActiveRecord\Model {
static $belongs_to = array(
array('user'));
}

$user = User::find_by_first_name('john');
$role = Role::find_by_role('admin');

$user->role_id = $role->id;
$user->save();

Is there a better / more effective way than this ??

Benjamin P Thu Nov 25 03:49:12 -0500 2010

$user->link($role);

wouldn't be enough, IMO, as a model can have many associations (and even many associations to models of the same type). So I'd rather propose:

$user->link('role', $role);
$user->unlink('role', $role);

or:

$user->addRole($role);
$user->removeRole($role);

(1-4/4)