在Rails 3.1中,我应该如何为具有大量模型的模型格式化ActiveRecord关联声明?
问题描述:
在我的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]与它生活 - 每个人的模型文件这个样子。
答
一般的经验法则是垂直对齐相关的赋值。这也贯穿到相关的声明中。
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
答
是有可能将它们分组,由你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
下一步可以进行相应的努力使这些模块相当无关,和组你的测试。
答
你可以有一个模型有很多的关联,这对我来说很好。如果背后有一个复杂的逻辑,会导致一系列复杂的关联。例如,我有一个拥有超过60个协会的帐户类:用户,公司,中心,产品,文档,路线,车辆......
此问题更多关于可读性。首先,决定一个约定,并在整个项目中遵循相同的规则(belongs_to第一,has_one第二,has_many第三,habtm最后) 第二个建议:如果某些关系明确与良好分离的功能相关,则可以拆分你的类分成一些模块,保持模块中的每个关系。但这是一条通用规则。
class Account < ActiveRecord::Base
include Account::CRM
include Account::Plans
include Account::Finances
end
答
也许你可以将父母模型分发给其他人......
例子,我有一个使用用户的三种不同情况下的应用程序:
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
同为TasksProfile
和BankAccount
。
你能举一个这些是什么样的资源的例子吗?一个模型中的32个关联看起来很荒唐,我从来没有见过这样的事情! –
[b]如果你有很多关联,你的模型显然有问题。 – Henrik
@AshleyWilliams - 一个这样的资源是'书',它has_many:作者,:语言,:流派,:类别,:主题,:译者,:标签,:标识符,评论...以及其他特定于此应用程序的其他人,以及他们:通过协会。 – GladstoneKeep