Permalink
Browse files

Persist LineItems on Reimbursements

  • Loading branch information...
danielfone committed Oct 19, 2013
1 parent 257d3f2 commit 1ed5f8176087a1ca72917531792fc744f10f14bb
Showing with 22 additions and 2 deletions.
  1. +1 −1 app/controllers/reimbursements_controller.rb
  2. +21 −1 app/models/reimbursement.rb
@@ -69,6 +69,6 @@ def set_reimbursement
# Never trust parameters from the scary internet, only allow the white list through.
def reimbursement_params
params.require(:reimbursement).permit(:reference, :payee_id, :comments, :data)
params.require(:reimbursement)
end
end
@@ -1,10 +1,30 @@
class Reimbursement < ActiveRecord::Base
belongs_to :payee, class_name: 'Employee'
store :data, coder: JSON
store_accessor :data, :line_items_attributes
validates :payee_id, presence: true
validate :check_line_items
def line_items
@line_items ||= []
@line_items ||= if line_items_attributes
line_items_attributes.map { |attrs| LineItem.new attrs }
else
[]
end
end
def line_items_attributes=(data)
super data.values.reject { |attrs| attrs['detail'].blank? }

This comment has been minimized.

Show comment
Hide comment
@danielfone

danielfone Oct 20, 2013

Owner

We need data.values because the form data is passed in as a hash of { id => attributes }, e.g.

{
  "0"=>{"detail"=>"Testing", "code"=>"", "dept"=>"", "amount"=>"", "gst"=>"0"},
  "1"=>{"detail"=>"Testing 2", "code"=>"", "dept"=>"", "amount"=>"", "gst"=>"0"},
}

Since our order is persistent, we don't care about IDs and simply serialise the hash values, which becomes an array of attributes.

.reject { |attrs| attrs['detail'].blank? } will ignore any lines that have a blank details field. This means we won't try to validate and persist completely blank lines, and we can remove existing lines by blanking the detail field.

@danielfone

danielfone Oct 20, 2013

Owner

We need data.values because the form data is passed in as a hash of { id => attributes }, e.g.

{
  "0"=>{"detail"=>"Testing", "code"=>"", "dept"=>"", "amount"=>"", "gst"=>"0"},
  "1"=>{"detail"=>"Testing 2", "code"=>"", "dept"=>"", "amount"=>"", "gst"=>"0"},
}

Since our order is persistent, we don't care about IDs and simply serialise the hash values, which becomes an array of attributes.

.reject { |attrs| attrs['detail'].blank? } will ignore any lines that have a blank details field. This means we won't try to validate and persist completely blank lines, and we can remove existing lines by blanking the detail field.

end
private
def check_line_items
line_items.each_with_index do |li, i|
errors.add "Line Item #{i+1}:", li.errors.full_messages.to_sentence unless li.valid?
end
end
end

0 comments on commit 1ed5f81

Please sign in to comment.