I have trouble with the self referential association, the models should give ma an array of models for the left_chunks and right_chunks methods, but I get everytime an empty array
The source
class Chunk < ActiveRecord::Base
has_many :left_bindings, :foreign_key => "left_chunk_id",
:class_name => "ChunkChunk",
:dependent => :destroy
has_many :right_chunks, :through => :left_bindings
has_many :right_bindings, :foreign_key => "right_chunk_id",
:class_name => "ChunkChunk",
:dependent => :destroy
has_many :left_chunks, :through => :right_bindings
end
class ChunkChunk < ActiveRecord::Base
belongs_to :left_chunk, :class_name => "Chunk", :foreign_key => "left_chunk_id"
belongs_to :right_chunk, :class_name => "Chunk", :foreign_key => "right_chunk_id"
end
Output from ./script/console
>> #first case
?>
?> left = Chunk.new({:content => "chunk_one"}); left.save
=> true
>> right = Chunk.new({:content => "chunk_two"}); right.save
=> true
>> left.right_chunks << right
=> []
>> left.right_chunks
=> []
>> left.left_chunks
=> []
>>
?> #second case
?>
?> left = Chunk.new({:content => "chunk_three"}); left.save
=> true
>> right = Chunk.new({:content => "chunk_four"}); right.save
=> true
>> right.left_chunks << left
=> []
>> right.left_chunks
=> []
>> right.right_chunks
=> []
Why are the chunks not bound together ?
Database after code execution
mysql> select * from chunks;
+----+-------------+---------------------+---------------------+
| id | content | created_at | updated_at |
+----+-------------+---------------------+---------------------+
| 1 | chunk_one | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
| 2 | chunk_two | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
| 3 | chunk_three | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
| 4 | chunk_four | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
+----+-------------+---------------------+---------------------+
mysql> select * from chunk_chunks;
+----+---------------+----------------+---------------------+---------------------+
| id | left_chunk_id | right_chunk_id | created_at | updated_at |
+----+---------------+----------------+---------------------+---------------------+
| 1 | NULL | 2 | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
| 2 | 3 | NULL | 2010-02-14 12:11:22 | 2010-02-14 12:11:22 |
+----+---------------+----------------+---------------------+---------------------+
Any ideas ?