Has_many : Self Referential Association을 통해
-
20-09-2019 - |
문제
나는 자체 참조 연관에 문제가 있는데, 모델은 ma ma에 왼쪽_chunks 및 right_chunks 메소드에 대한 모델 배열을 제공해야하지만 빈 배열마다 얻을 때마다 얻을 수 있습니다.
출처
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
./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
=> []
덩어리가 함께 묶이지 않는 이유는 무엇입니까?
코드 실행 후 데이터베이스
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 |
+----+---------------+----------------+---------------------+---------------------+
어떤 아이디어?
해결책
당신은 어떤 버전의 mySQL, 루비 또는 레일을 말하지 않습니다. 방금 작은 테스트 응용 프로그램으로 이것을 시도했는데 올바르게 작동했습니다. OS X 10.6에서 PostgreSQL 8.4.1을 사용하고 있습니다. 방금 Rails 2.3.5 / Ruby 1.8.7 (2009-06-12 Patchlevel 174)에서 빈 앱을 만들었습니다.
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
... and chunk_chunks.rb :
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
... 간결함을위한 타임 스탬프없이 테이블을 추가하기위한 두 가지 마이그레이션과 :
class AddChunks < ActiveRecord::Migration
def self.up
create_table 'chunks' do | t |
t.string :content
end
end
def self.down
drop_table 'chunk'
end
end
...그리고:
class AddChunkChunks < ActiveRecord::Migration
def self.up
create_table 'chunk_chunks' do | t |
t.belongs_to :left_chunk
t.belongs_to :right_chunk
end
end
def self.down
end
end
그런 다음 "Rake DB : Create", "Rake DB : Migrate"를 실행했으며 콘솔 명령은 다음과 같이 저에게 작동했습니다.
PondPro:testapp adh1003$ script/console
Loading development environment (Rails 2.3.5)
>> left = Chunk.new({:content => "chunk_one"}); left.save
=> true
>> right = Chunk.new({:content => "chunk_two"}); right.save
=> true
>> left.right_chunks << right
=> [#<Chunk id: 2, content: "chunk_two">]
>> left.right_chunks
=> [#<Chunk id: 2, content: "chunk_two">]
>> left.left_chunks
=> []
>> left = Chunk.new({:content => "chunk_three"}); left.save
=> true
>> right = Chunk.new({:content => "chunk_four"}); right.save
=> true
>> right.left_chunks << left
=> [#<Chunk id: 3, content: "chunk_three">]
>> right.left_chunks
=> [#<Chunk id: 3, content: "chunk_three">]
>> right.right_chunks
=> []
위의 데이터베이스 내용은 다음과 같습니다.
chunk-devel=# SELECT * FROM chunks;
id | content
----+-------------
1 | chunk_one
2 | chunk_two
3 | chunk_three
4 | chunk_four
(4 rows)
chunk-devel=# SELECT * FROM chunk_chunks;
id | left_chunk_id | right_chunk_id
----+---------------+----------------
1 | 1 | 2
2 | 3 | 4
(2 rows)
이것을 감안할 때 :
...이:
... 원래 코드에서는 실제로 잘못된 것을 볼 수 없습니다. 아마도 마이그레이션은 당신이 기대하는 것이 아닙니다. 아마도 당신이 게시하지 않은 코드의 다른 부분이 방해하지 않는 다른 부분 (예 : 필터, 다른 보석) 또는 MySQL의 ActiveCord 데이터베이스 어댑터 가이 경우 올바른 일을하지 않을 것입니다. 및/또는 MySQL은 제대로 작동하지 않습니다. PostgreSQL을 설치하고 추가 테스트를 위해 MySQL 대신에 사용하는 것은 약간 오래 걸리지 만 가치가 있다고 생각합니다.
유용한 것으로 판명 된 경우 여기에 테스트 응용 프로그램 데이터를 업로드했습니다.
무엇이 잘못되었는지 알아 내고 수정하려면 여기에 후속 조치를 게시하십시오. 이것은 누군가가 미래에 비슷한 문제에 직면하고 솔루션을 검색하는 동안이 스레드를 읽는 경우 유용합니다.
다른 팁
이것이 .Reload 문제입니까? 콘솔 에서이 작업을 수행 한 후 :
right.left_chunks << left
하다
right.reload
그런 다음 시도하십시오
right.left_chunks
.