A
A
Arkady Butermanov2014-01-31 00:02:08
Ruby on Rails
Arkady Butermanov, 2014-01-31 00:02:08

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

It is clear that each model has an auto_increment :id field, which is used as the primary key. But what if I want to know the number of Item'a related to a specific user (Ie, there must be some field that is automatically numbered within one user). Those. for each user the numbering of Items must start from one.
How to solve such a problem? Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ivan Kryak, 2014-01-31
@Arkadey

have you looked at acts_as_list?

C
Cepega, 2014-01-31
@Cepega

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

S
SergeyMild, 2014-02-04
@SergeyMild

belongs_to : user, counter_cache: true

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question