Should rail models relate to other models for skinny controllers?

I read everywhere that business logic belongs to models, not to the controller, but where is the limit? I play with a personal account.

Account
Entry
Operation

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

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

Now the form displayed to the user in the case of basic operations is simplified to hide the data of records, accounts are selected from 5 by default according to the type of operation requested by the user (intialise account → equity for accout, spend assets → expenses, earn income → assets, take on liabilities themselves → assets, pay debt assets → liabilities ...) I want the records to be created from the default values.

( 2 ). , . Entry.

? SimpleOperationController, , Operation, Operation.new_simple_operation (params [: operation])

, Entry Operation?

:)

edit - , . . , :

, , : , , . , .

#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

,

def spend
  op=Operation.new_simple_operation(params)
  op.save
end

, , .

+5
5

, .

?

"-" , , , , , Operation Entry.

, , , , , EntryHtmlFormBuilder - : -)

+6

( ) . . .

class Operation
  has_many :entries

  def entry_attributes=(entry_attributes)
    entry_attributes.each do |entry|
      entries.build(entry)
    end
  end

end

class OperationController < ApplicationController
  def create
    @operation = Operation.new(params[:opertaion])
    if @operation.save
      flash[:notice] = "Successfully saved operation."
      redirect_to operations_path
    else
      render :action => 'new'
    end
  end
end

, . . , "", , , Operation:

class Operation
  # methods from above
  protected
    def validate
      total = 0
      entries.each { |e| t += e.amount }
      errors.add("entries", "unbalanced transfers") unless total == 0
    end
end

, , , . , , , , .

+2

, , . , :

class Operation < ActiveRecord::Base
  has_many :entries
  validates_associated :entries
end

validates_associated , ( , ).

, , , , , , , .

0

, , , reponses, . , / . (2 ), 2 . , , , . Operation, , AR, -, . , , - , . lib/, Rails .

0
source

If you are concerned about embedding this logic in any particular model, why not put it in an observer class that will preserve the logic for your creation of related elements separately from the observed classes.

0
source

All Articles