Arild Tvergrov Wed Jan 18 06:10:54 -0500 2012

Subject: Can't build/create instances of many-to-many associations

Hi, I can't seem to figure out how to build or create instances of many-to-many associations. In my project, I have a many-to-many association between the models Researcher and Country, through the table countries_researchers.

lev_researchers
--------------------------------------
id
first_name
last_name
...
lev_countries
--------------------------------------
id
name
lev_countries_researchers
--------------------------------------
researcher_id
country_id

The model declarations are as follows:

class Researcher extends ActiveRecord\Model {
static $table_name = 'lev_researchers';
static $has_many = array(
array('country_researcher'),
array('countries', 'through' => 'country_researcher')
);
}
class Country extends ActiveRecord\Model {
static $table_name = 'lev_countries';
static $has_many = array(
array('country_researcher'),
array('researchers', 'through' => 'country_researcher')
);
}
class CountryResearcher extends ActiveRecord\Model {
static $table_name = 'lev_countries_researchers';
static $belongs_to = array(
array('researcher'),
array('country')
);
}

If I add rows manually with SQL and use PHP-AR finders, the association seems to work perfectly and I'm able to get the countries with which the researchers are tagged, using $researcher->countries(). However, when I try to create/build a new researcher with an association to the country model, the script fails. Here's the script:

$res = new Researcher($_POST['researcher']);
$country = Country::find_by_name('Norway');
$res->build_countries(array($country));
$res->save();

Norway is already in the database, and I've checked that it returns an object of that country. Here's the error message:

Undefined property: Country->0 in [...]/active-record/lib/Model.php on line 428

Why does it look for a property named "0"? Am I missing something?

Thanks in advance!

Edit: I'm using PGSQL v9.1 and PHP v5.3.8.