6

I'm using Ryan Bates nested_form gem. I'd like to be able to control the ordering that it lists the nested fields in. I have a default_scope that works, but I need more control over this depending on the scenario.

Ideally something like

# In controller action
@nesties = Nesty.order("name desc")

# In view
# If @nesties defined the following line would respect the @nesties ordering
f.fields_for :nesties do |nestie-form|

Right now it will respect the default_scope ordering, but I can't find any other way to control the ordering.

jfeust
  • 845
  • 1
  • 9
  • 19

5 Answers5

16

Note that fields_for accepts a second argument, and that is where the named scope can be specified when specifying the objects/association to use. The following worked for me. Rails 3.x

#In Model Nestie
scope :ordered_nesties, order("name DESC")
belongs_to :parent

#In Model Parent
has_many :nesties

#In View
f.fields_for :nesties, @parent.nesties.ordered_nesties do |nestie-form|

Hope this helps.

  • See ['scope body needs to be callable'](http://stackoverflow.com/questions/28951671/argument-error-the-scope-body-needs-to-be-callable) and after that syntax correction, this solution worked wonderfully for me. – AOphagen Jun 09 '15 at 17:11
7

In the model that has the nesties association:

has_many :nesties, :order => "name DESC"

This may be too global for your app though.

But the fundamental thing is that fields_for doesn't pick up on @nesties it picks up on association of the parent form's model.

EDIT: Not sure this would work with the nested_form gem but this solution wouldn't affect the normal ordering of the nesties association:

named_scope :ordered_nesties, :order => "name DESC"

then

f.fields_for :ordered_nesties do |nestie-form|
Erik Petersen
  • 2,347
  • 14
  • 17
  • 1
    I couldn't get scope/named_scope to work as a symbol to f.fields_for, but the :order on the association does work. Unfortunately it doesn't offer much more control than just using default_scope, but thanks for the info. – jfeust May 14 '12 at 21:13
1

FYI, this thing worked for me without making the scope

f.fields_for :nesties, @parent.nesties.ordered("name DESC") do |nestie-form|
jimagic
  • 4,045
  • 2
  • 28
  • 49
1

I was able to get my nested form objects ordered using the following method. Hopefully, it helps someone else...

<%= form.nested_fields_for :evaluations, 
      form.object.evaluations.target.sort_by! { |e| e.skill.sort } do |f| %>
daveomcd
  • 6,367
  • 14
  • 83
  • 137
0

nested_form gem seems to have a strange behavior ( it's a bug in my opinion). When given a collection to render - it sorts it by "id" before rendering. It might be transparent to most, but is quiet unpleasant in some situations.

Solution given above by Shantanu solves that problem by directly providing the collection to fields_for to render and effectively bypassing the nested_forms iterator.

I wasted 2+ hours trying to resolve this .. Thanks Shantanu!

John Doe
  • 199
  • 1
  • 8