Search code examples
ruby-on-railsrails-activerecordsimple-form

Ordering nested attributes


I am looking to order nested attributes:

I have a Budget model with nested attributes:

has_many :budget_items, dependent: :destroy

I am using the simple_form gem and a basic nested attributes form that work perfectly fine:

f.simple_fields_for :budget_items do |i|
  ...
end

By default it looks to me that Active Record defaults to sorting by the updated_at attribute.

I had dabbled with this before and tried this approach:

f.simple_fields_for :budget_items, @budget.budget_items.order(:some_attribute) do |i|
  ...
end

This sort of works but breaks the automatic form field validation css changes. Normally then if I leave a nest field blank etc. when the form fails validation the fields are highlighted red etc. If you pass in the optional collection the nested form works but validations fail.

I had a lightbulb moment where I tried this:

  has_many :budget_items, -> { joins(...).order(..) }, dependent: :destroy

basically adding a scope with the order in the association. In my case my order is a complicated one but it works - in development only. Once I deploy this to production the order seems to be completely random vs. by the updated_at.

Lots going on here - by biggest question is why does this work flawless in development and then falls apart in production?


Solution

  • The solution I was using actually works i.e. the -> {} scope method. After some digging the join -> order I had was in fact the issue. The dummy data I had in my development env wasn't sufficient for me to see that.