2011-10-22 2 views
0

내 Rails 3.1 프로젝트에는 많은 연관이있는 모델이 있습니다. 액티브 협회 선언을 사용하여, 나는 다음과 같이 모델 파일로 끝날 :Rails 3.1에서는 많은 모델이있는 ActiveRecord 연관 선언을 어떻게 포맷해야합니까?

# app/models/some_model.rb 

class SomeModel < ActiveRecord::Base 
    belongs_to :other_model 
    has_many :more_models 
    has_many :yet_more_models, :through => :more_models 
    has_one :another_model, :dependent => :destroy 

    # ... these declarations continue, 
    # and continue, 
    # and continue, 
    # all the way down to line 32 
end 

이 빠르게 대단히 추한되고 내 이해/동기 부여/행복을 꺾습니다. 완화하려면 어떻게해야합니까?

  • [A] 형식/그룹/특정 방법으로 그들을 들여?
  • [B] 다시 생각이
  • 는 [C] 그것으로 라이브 가난한 디자인의 증상 일 수 있으므로, 내 데이터 모델을 - 모든 사람의 모델 파일이 방법을 찾습니다.
+0

이러한 자원의 종류에 대한 예를들 수 있습니까? 한 모델의 32 개 협회는 어리석은 것처럼 보입니다. –

+0

[b] 많은 연관이있는 경우 모델에 분명히 잘못된 것이 있습니다. – Henrik

+0

@AshleyWilliams -이 리소스 중 하나는 has_many : authors, : languages, : genres, : categories, : subjects, : translators, : tags, : identifiers, : reviews ... 및이 응용 프로그램과 관련된 기타 , 그리고 그들의 : 협회를 통해. – GladstoneKeep

답변

0

일반적인 규칙은 관련 할당을 세로로 정렬하는 것입니다. 그것은 관련된 선언들까지도 전달합니다. 당신이 자세한 생각한다면

class SomeModel < ActiveRecord::Base 
    belongs_to :other_model 
    has_many :more_models 
    has_many :yet_more_models, :through => :more_models 
    has_one :another_model, :dependent => :destroy 
end 

, 당신이 보지 DataMapper 모델 : P

1

은 당신의 SomeModel의 다양한 측면/기능에 의해, 그룹화 할 수 있습니까? 이 그룹의 모임은 SomeModel 클래스에 상당히 많은 수반되는 방법을 사용하는 경향이 있습니까? 그렇다면 모델을 여러 특성 (예 : 특성)으로 나눠서, 모든 측면에 하나씩, 클래스 메소드 및 연관 선언을 포함한 모든 것을 묶어서 도울 수 있습니다.

class SomeModel 
    include SomeModel::ThisBehavior 
    include SomeModel::ThatFeature 
end 

module SomeModel::ThisBehavior 
    extend ActiveSupport::Concern 

    included do 
    has_many :this 
    has_many :that 
    belongs_to :those 

    attr_protected :a, :b 
    attr_accessor :c, :d 
    end 

    def do_this 
    end 

    ... 

    module ClassMethods 
    ... 
    end 
end 

은 다음 단계는 그에 따라 시험을하는 모듈은 매우 불가지론 만들려고 노력하고, 그룹 수 있습니다.

0

많은 연관성이있는 모델을 만들 수 있으며 나에게 좋습니다. 복잡한 논리가 뒤따른다면 복잡한 연관성이 생길 것입니다. 예를 들어, 사용자, 회사, 센터, 제품, 문서, 노선, 차량 등 60 개가 넘는 협회가있는 Account 클래스가 있습니다 .....

이 질문은 가독성에 대한 것입니다. 먼저, 대회를 결정하고 프로젝트 전체에 동일한 규칙을 따르십시오 (belongs_to first, has_one second, has_many third, habtm last). 두 번째 조언 : 일부 관계가 잘 분리 된 기능과 분명하게 관련되어 있으면 클래스를 분리 할 수 ​​있습니다 어떤 모듈로 각 관계를 유지하는 모듈로. 그러나 이것은 일반적인 규칙입니다.

class Account < ActiveRecord::Base 
    include Account::CRM 
    include Account::Plans 
    include Account::Finances  

end 
0

어쩌면 부모 모델을 다른 사람들에게 배포 할 수 있습니다.다른 프로젝트 범위에서 사용자를 나타내는

class User < ActiveRecord::Base 
    has_one :social_profile 
    has_one :tasks_profile 
    has_one :bank_account 
end 

그리고 다른 모델 : TasksProfileBankAccount에 대한

class SocialProfile < ActiveRecord::Base 
    belongs_to :user 
    has_many :many_things 
    ... 
end 

같은

예, 나는 사용자의 세 가지 다른 인스턴스를 사용하는 응용 프로그램을 가지고있다.

관련 문제