1

내 프로젝트에 이상한 요구 사항이 있습니다. 실제로 두 테이블 (사용자, 갤러리)이 있습니다. has_one 및 has_many 연관을 사용하여 갤러리 테이블에 액세스하고 싶습니다. 주요 목적은 has_one 관계를 사용하여 사용자의 프로필 스냅을 가져오고 has_many 관계를 사용하여 개인적으로 업로드 한 그림을 가져 오는 것입니다.두 테이블 간의 Buid 두 연관

처음에는이 문제를 해결하기 위해 다형성 연관을 사용합니다 (참고로 아래 코드를 찾으십시오.)하지만이 문제에 대한 올바른 접근 방법은 아닌 것 같습니다.

아무도 효율적인 방법으로이 사건을 처리하는 방법을 설명하지 않겠습니까?

class User < ActiveRecord::Base 
    attr_accessible :name 
    has_many :galaries, as: :imageable 
    has_one :galary, as: :imageable 
end 

class Galary < ActiveRecord::Base 
    attr_accessible :name 
    belongs_to :imageable, polymorphic: true 
end 

답변

1

당신은 galary (프로파일 스냅)에 사용자를 연결하기 위해 galaries 테이블의 열 user_id를 추가해야합니다.

rails generate migration add_user_id_to_galaries user_id:string 

이 마이그레이션 생성합니다

class User < ActiveRecord::Base 
    attr_accessible :name 
    has_many :galaries, as: :imageable 
    has_one :galary #profile snap 
end 

class Galary < ActiveRecord::Base 
    attr_accessible :name 
    belongs_to :imageable, polymorphic: true 
    belongs_to :user #profile snap user 
end 
+0

당신은 다형성과 has_one 조합을 유지해야합니다. class_name 등을 사용하여 대안이 있습니까? – pramod

+1

사용자 has_many : galaries가 이미 있기 때문에 클래스 이름에서 식별하지 못합니다. – mohameddiaa27

+0

절대적으로 has_many 등에서 class_name을 배치하는 것과 같은 대안이 있습니까? – pramod

0

이 범위 has_one 엉덩이를 수행 할 수 있습니다 :

class AddUserIdToGalaries < ActiveRecord::Migration 
    def change 
    add_column :galaries, :user_id, :integer 
    end 
end 

그럼 지금 우리의 모델로 이동 rake db:migrate


을 실행을 눈. 필요하지는 않지만 범위를 사용하여 has_one에서 어느 gallery이 선택되어 있는지 정의 할 수 있습니다. 범위를 지정하지 않으면 has_one이 첫 번째 일치 항목을 반환합니다.

class User < ActiveRecord::Base 
    attr_accessible :name 
    has_many :gallaries 
    has_one :gallery, -> { where primary: true } 
end 

class Gallery < ActiveRecord::Base 
    #user_id, primary (boolean variable to select the gallery in has one association) 
    attr_accessible :name 
    belongs_to :user 
end