Paul
Paul

Reputation: 26660

Auto increment field while creating Rails association object

I am creating Rails model objects by referencing them through association:

class MyRequest < ActiveRecord::Base
   has_many :my_request_addresses
   def self.fill
      self.my_request_addresses.create(parameters)
   end
end

MyRequestAddress model has one integer field which should indicate route points' order in request. This field should be incremented starting from 1 with each new address created, so the first created address wil be 1, the second - 2 etc.

Is there some built-in Rails mechanism to achieve the goal?

Upvotes: 0

Views: 635

Answers (1)

Juanito Fatas
Juanito Fatas

Reputation: 9969

Yes and it's called counter_cache.

http://guides.rubyonrails.org/association_basics.html 4.1.2.3

Upvotes: 1

Related Questions