ActiveRecord::Schema.define do
create_table :todo_lists do; end
create_table :todo_items do |t|
t.references :todo_list, null: false
t.integer :priority, default: 1, null: false
t.index [:todo_list_id, :priority], unique: true
end
end
FactoryBot.define do
factory :todo_item do
scoped_sequence(:priority, :todo_list_id)
end
end
attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>1}
attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>2} # generate attribute value `priority` sequentially
attributes_for(:todo_item, todo_list_id: 2) # => {:todo_list_id=>2, :priority=>1} # when value of scope attribute is different, another sequential number is generated.
attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>3}
New feature useful in the following case