Search code examples
ruby-on-railsrubyruby-on-rails-4nested-attributes

Rails: Ordering in nested form


I have a profile model that accept experience model as a nested attributes, and i want to order experience by experience_end_date this is my profile model

has_many :experiences, dependent: :destroy, :order => ("experience_end_date")
accepts_nested_attributes_for :experiences

but this is don't work can some one help in how can i fix this?

the experience_end_date is a date field column in the experience model


Solution

  • This is how you specify the order:

    has_many :experiences,
             ->{ order(:experience_end_date) },
             dependent: :destroy
    

    That will sort by ascending; for descending do this:

    has_many :experiences,
             ->{ order("experience_end_date DESC") },
             dependent: :destroy
    

    You can usually find answers to such questions in the documentation, either in explanations or in the example code snippets.