2011-10-22 53 views
0

在我的Rails 3.1項目中,我有一些有很多關聯的模型。使用ActiveRecord協會的聲明,我結束了看起來像這樣的模型文件:在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:作者,:語言,:流派,:類別,:主題,:譯者,:標籤,:標識符,評論...以及其他特定於此應用程序的其他人,以及他們:通過協會。 – 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個協會的帳戶類:用戶,公司,中心,產品,文檔,路線,車輛......

此問題更多關於可讀性。首先,決定一個約定,並在整個項目中遵循相同的規則(belongs_to第一,has_one第二,has_many第三,habtm最後) 第二個建議:如果某些關係明確與良好分離的功能相關,則可以拆分你的類分成一些模塊,保持模塊中的每個關係。但這是一條通用規則。

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 

等車型,代表用戶在其他項目的範圍:

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

同爲TasksProfileBankAccount

相關問題