Rails order nested_form

I am using Ryan Bates nested_form gem . I would like to be able to control the order in which it inserts the nested fields. 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|

Now he will respect the default order, but I cannot find another way to control the order.

+5
source share
5 answers

In a model that has a nest association:

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

This may be too global for your application.

But the main thing is that fields_for does not select @nesties, it selects a relationship with the model of the parent form.

EDIT: , nested_form, :

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

f.fields_for :ordered_nesties do |nestie-form|
+7

, fields_for , , / . . 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|

, .

+12

FYI,

f.fields_for :nesties, @parent.nesties.ordered("name DESC") do |nestie-form|
+1

, . , - ...

<%= form.nested_fields_for :evaluations, 
      form.object.evaluations.target.sort_by! { |e| e.skill.sort } do |f| %>
+1

( ). - ​​ "id" . , .

The solution given above by Shantanu solves this problem by directly providing the fields_for assembly for rendering and efficient traversal of the nested_forms iterator.

I spent 2 hours resolving this. Thanks Shantanu!

0
source

All Articles