<p>I read everywhere that business logic belongs in the models and not in controller but where is the limit?
I am toying with a personnal accounting application. </p>

<pre><code>Account
Entry
Operation
</code></pre>

<p>When creating an operation it is only valid if the corresponding entries are created and linked to accounts so that the operation is balanced for exemple buy a 6-pack :</p>

<pre><code>o=Operation.new({:description=&gt;"b33r", :user=&gt;current_user, :date=&gt;"2008/09/15"})
o.entries.build({:account_id=&gt;1, :amount=&gt;15})
o.valid? #=&gt;false
o.entries.build({:account_id=&gt;2, :amount=&gt;-15})
o.valid? #=&gt;true
</code></pre>

<p>Now the form shown to the user in the case of <em>basic operations</em> is simplified to hide away the entries details, the accounts are selected among 5 default by the kind of operation requested by the user (intialise account -> equity to accout, spend assets->expenses, earn revenues->assets, borrow liabilities->assets, pay debt assets->liabilities ...) I want the entries created from default values.</p>

<p>I also want to be able to create more complex operations (more than 2 entries). For this second use case I will have a different form where the additional complexity is exposed.This second use case prevents me from including a debit and credit field on the Operation and getting rid of the Entry link. </p>

<p>Which is the best form ? Using the above code in a SimpleOperationController as I do for the moment, or defining a new method on the Operation class so I can call Operation.new_simple_operation(params[:operation])</p>

<p>Isn't it breaking the separation of concerns to actually create and manipulate Entry objects from the Operation class ?</p>

<p>I am not looking for advice on my twisted accounting principles :)</p>

<p>edit -- It seems I didn't express myself too clearly. 
I am not so concerned about the validation. I am more concerned about where the creation logic code should go : </p>

<p>assuming the operation on the controller is called spend, when using spend, the params hash would contain : amount, date, description. Debit and credit accounts would be derived from the action which is called, but then I have to create all the objects. Would it be better to have </p>

<pre><code>#error and transaction handling is left out for the sake of clarity
def spend
  amount=params[:operation].delete(:amount)#remove non existent Operation attribute
  op=Operation.new(params[:operation])
  #select accounts in some way
  ...
  #build entries
  op.entries.build(...)
  op.entries.build(...)
  op.save
end
</code></pre>

<p>or to create a method on Operation that would make the above look like </p>

<pre><code>def spend
  op=Operation.new_simple_operation(params)
  op.save
end
</code></pre>

<p>this definitely give a much thinner controller and a fatter model, but then the model will create and store instances of other models which is where my problem is.</p>

[{'answer_id': 64389, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>It's easier to think in terms of each entity validating itself, and entities which depend on one another delegating their state to the state of their associated entries. In your case, for instance:</p>\n\n<pre><code>class Operation &lt; ActiveRecord::Base\n  has_many :entries\n  validates_associated :entries\nend\n</code></pre>\n\n<p>validates_associated will check whether each associated entity is valid (in this case, all entries should if the operation is to be valid).</p>\n\n<p>It is very tempting to try to validate entire hierarchies of models as a whole, but as you said, the place where that would be most easily done is the controller, which should act more as a router of requests and responses than in dealing with business logic.</p>\n"}, {'answer_id': 66025, 'author': 'Michael Latta', 'author_id': 9679, 'author_profile': 'https://Stackoverflow.com/users/9679', 'pm_score': 0, 'selected': False, 'text': '<p>The way I look at it is that the controller should reflect the end-user view and translate requests into model operations and reponses while also doing formatting.  In your case there are 2 kinds of operations that represent simple operations with a default account/entry, and more complex operations that have user selected entries and accounts.  The forms should reflect the user view (2 forms with different fields), and there should be 2 actions in the controller to match.  The controller however should have no logic relating to how the data is manipulated, only how to receive and respond.  I would have class methods on the Operation class that take in the proper data from the forms and creates one or more object as needed, or place those class methods on a support class that is not an AR model, but has business logic that crosses model boundaries.  The advantage of the separate utility class is that it keeps each model focused on one purpose, the down side is that the utility classes have no defined place to live.  I put them in lib/ but Rails does not specify a place for model helpers as such.</p>\n'}, {'answer_id': 66985, 'author': 'Sixty4Bit', 'author_id': 1681, 'author_profile': 'https://Stackoverflow.com/users/1681', 'pm_score': 2, 'selected': False, 'text': '<p>Virtual Attributes (more info <a href="http://railscasts.com/episodes/16" rel="nofollow noreferrer">here</a> and <a href="http://railscasts.com/episodes/73" rel="nofollow noreferrer">here</a>) will help with this greatly. Passing the whole params back to the model keeps things simple in the controller. This will allow you to dynamically build your form and easily build the entries objects.</p>\n\n<pre><code>class Operation\n  has_many :entries\n\n  def entry_attributes=(entry_attributes)\n    entry_attributes.each do |entry|\n      entries.build(entry)\n    end\n  end\n\nend\n\nclass OperationController &lt; ApplicationController\n  def create\n    @operation = Operation.new(params[:opertaion])\n    if @operation.save\n      flash[:notice] = "Successfully saved operation."\n      redirect_to operations_path\n    else\n      render :action =&gt; \'new\'\n    end\n  end\nend\n</code></pre>\n\n<p>The save will fail if everything isn\'t valid. Which brings us to validation. Because each Entry stands alone and you need to check all entries at "creation" you should probably override validate in Operation:</p>\n\n<pre><code>class Operation\n  # methods from above\n  protected\n    def validate\n      total = 0\n      entries.each { |e| t += e.amount }\n      errors.add("entries", "unbalanced transfers") unless total == 0\n    end\nend\n</code></pre>\n\n<p>Now you will get an error message telling the user that the amounts are off and they should fix the problem. You can get really fancy here and add a lot of value by being specific about the problem, like tell them how much they are off.</p>\n'}, {'answer_id': 67077, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 4, 'selected': True, 'text': "<blockquote>\n  <p>but then the model will create and store instances of other models which is where my problem is.</p>\n</blockquote>\n\n<p>What is wrong with this? </p>\n\n<p>If your 'business logic' states that an Operation must have a valid set of Entries, then surely there is nothing wrong for the Operation class to know about, and deal with your Entry objects.</p>\n\n<p>You'll only get problems if you take this too far, and have your models manipulating things they <em>don't</em> need to know about, like an EntryHtmlFormBuilder or whatever :-)</p>\n"}, {'answer_id': 103811, 'author': 'fatgeekuk', 'author_id': 17518, 'author_profile': 'https://Stackoverflow.com/users/17518', 'pm_score': 0, 'selected': False, 'text': '<p>If you are concerned about embedding this logic into any particular model, why not put them into an observer class, that will keep the logic for your creation of the associated items separate from the classes being observed.</p>\n'}]
['https://Stackoverflow.com/questions/64214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7898/']