Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails nested_form ordering

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.

like image 475
jfeust Avatar asked May 11 '12 21:05

jfeust


3 Answers

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.

like image 100
Shantanu Kangude Avatar answered Nov 02 '22 15:11

Shantanu Kangude


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|
like image 30
Erik Petersen Avatar answered Nov 02 '22 15:11

Erik Petersen


FYI, this thing worked for me without making the scope

f.fields_for :nesties, @parent.nesties.ordered("name DESC") do |nestie-form|
like image 1
jimagic Avatar answered Nov 02 '22 16:11

jimagic