Answer the question
In order to leave comments, you need to log in
Additional auto_increment field in Rails model?
For example, there are two models:
class User < ActiveRecord::Base
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :user
end
Answer the question
In order to leave comments, you need to log in
class Item < ActiveRecord::Base
belongs_to :user
before_validation :set_user_increment_id, :on => :create
validates :user_increment_id, :presence => true, :uniqueness => {:scope => :user_id}
private
def set_user_increment_id
self.user_increment_id = self.class.where(:user_id => user_id).last.user_increment_id + 1 rescue 1
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question