ranked-model icon indicating copy to clipboard operation
ranked-model copied to clipboard

can't validate for presence

Open ngw opened this issue 12 years ago • 2 comments

Hi, I would like to ensure my ranked model never has nil in the ranked position, but for some reasons if I do that it doesn't populate the position attribute with a default value:

class Item < ActiveRecord::Base
  include RankedModel
  ranks :position

  validates :text, :position, presence: true
end

And these are my specs:

it "should not be valid without position" do
  @item.text = "Test text for item"
  @item.position = nil
  @item.should_not be_valid
  @item.should have( 1 ).errors_on( :position )
end

it "should have relevant default position" do
  @item.text = "Test text for item"
  @item.save
  @item.should be_valid
end

Results in:

should have relevant default position (FAILED - 1)
should not be valid without position

Failures:

1) Item creation: should have relevant default position
 Failure/Error: @item.should be_valid
   expected #<Item id: nil, text: "Test text for item", position: nil, created_at: nil, updated_at: nil> to be valid, but got errors: Position can't be blank
 # ./spec/models/item_spec.rb:25:in `block (3 levels) in <top (required)>'

Obviously if I remove the validation inside my model the default position is populated but the validation fails. Can I have both behaviors? Is this a bug?

ngw avatar Aug 14 '13 10:08 ngw

@ngw this looks like a bug, sure. I believe.

I'm having trouble parsing the statement "if I remove the validation inside my model the default position is populated but the validation fails". If you remove the validation of presence of position, then the record is valid and saved with a default value. But, if you explicitly set nil to position then you end up saving a nil value which is not desired. Confirmed?

mixonic avatar Aug 16 '13 01:08 mixonic

It means that it runs the validations before setting the default position, so if I put a validation in place it fails. I'm not sure what the best behavior would be, my 2 specs represent my best guess, where if I don't set a position explicitely I have a default value, but if I do and it's nil saving fails.

ngw avatar Aug 20 '13 09:08 ngw

Closing this. This is a column the gem user shouldn't be too concerned with. Trust that the code is well tested :D

brendon avatar Jun 04 '24 04:06 brendon