Search code examples
ruby-on-railsruby-on-rails-3mongoidmongoid3

Keep Child Objects sorted in a field_for


I have this kind of code:

user.posts.size #=> 5 already saved
user.posts.new(title:"foo")
user.posts.new(title:"bar")
user.posts.sort_by! { |e| e.title } #=> sort correclty
user.posts #=> sorted but with the saved on the top, the new one at the bottom

I use the sorting for field_for but obviously it's still unsorted.

Using: Rails 3.2.11 and Mongoid 3.0.23


Solution

  • I'm not sure about why it happens that way but i think this will do the trick

    # controller
    user.posts.build(title:"foo")
    user.posts.build(title:"bar")
    
    @posts = user.posts.sort_by(&:title)
    
    # view
    = f.fields_for :posts, @posts do |post_form|
      ...