开发者

Models in Rails are implicit, is this an annoying thing?

Considering models in Rails:

class Organizatio开发者_StackOverflow社区n < ActiveRecord::Base  
    belongs_to :OrgType  
end    

Does it bother you that models in Rails don't include the fields that made the entity? I know this is done for DRY's sake but you have to check the data base tables schema every time you want to check model's fields.


If you prefer a declarative style of ORM model, you might want to check out DataMapper or Sequel, both of which are easy to plug in to Rails 3.


Not annoying for me... ever since I started using the annotate-models gem to automatically add comments to the top of my model files, listing the fields associated with that model.


I was listening to a podcast a few months ago where the guy hosting the cast and the guest were advocating that Rails should take this path, and do away with migrations. The guy kept repeating "migrations must die", suggesting there be a way to specify your schema on the model instead.

I cannot disagree more, and I hope Rails never takes this path. Not only is it not DRY, but I like the fact that Rails encourages you to be aware of your own databases schema and structure.

In addition, there would be no way to keep a history of your schema if models were what controlled it, without having them be extremely cluttered. Migrations are essentially version control for your database that evolves with your application...and I wouldn't want to not have that.


Let's assume that OrgType has a field called position. This is common when you want to present a select list to the users who will be choosing a type. It's highly unlikely that your Organization will ever care about this field. Now extrapolate this to other related models with fields that other models don't care about, and add in the fact that if you ever wanted to change one of these fields you'd then have to hunt down each declaration of them, not just each place where they are used.

It's a mess.

Open up your db tool and look at your fields when you want to know what they are. Keep your models clean and readable. If you see code like this:

organization.org_type.name

It's pretty obvious that OrgType has a name field, without having to look it up, and without having to wade through configuration clutter in each model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜