Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

ruby - Rails: Skinny Controller vs. Fat Model, or should I make my Controller Anorexic?

I know similar questions have been answered before - such as:

  • Where should logic go
  • where to do certain tasks, etc.

But I have a more specific question - How far should I take this axiom: keep your controller skinny, make your model fat!

Here is an example:

For instance let's say I have multiple source of verification data. A good example would be a VIN number - I can verify it against, manufacturers data source, DMV's data source, also my local databases - to see what I have on record. So I have a model called Vin and vins_controller. Inside the model I have 5 methods:

  • check_against_local_db
  • check_against_dmv
  • check_against_car_maker_1
  • check_against_car_maker_2, etc.

In my controller keeping with the REST, in action show - I have a simple case statement which looks at the params[:source], and based on source specified - will call specific check method.

Now here is the question: Should I leave the logic that governs which data source to call in controller or should I move it to model and then in controller just do something like check_vin(source, vin)?

Should I make my controller anorexic?

EDIT

I'm switching this to official answer from @jay-godse ( thank you - at the time it was a good answer). Things changed a lot since 2010 and this question still gets some views - so hopefully this will point some people in the right direction and help them organize their code properly.

Trailblazer gem addresses problems brought up in the question really well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is an old saying,

Smart data structures and dumb code works a lot better than the other way around.

Everything you have described is about how one piece of data relates to another. That itself is your clue that the logic for those relationships, including validation should be in the model or database layer.

An anorexic controller is a sign of well-designed (smart?) data. My experience tells me that the more effort you put into designing your data, the less code you have to write overall.

Controllers are best at parsing inputs, calling the appropriate models, and then formatting the outputs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...