Fellow Stranger
Fellow Stranger

Reputation: 34023

Order the collection in a fields_for

A Controller has many Post.

In the view I'm iterating a controllers associated posts with the following:

<%= f.fields_for :posts do |builder|  %>
  <%= render 'post_fields', builder: builder %>
<% end %>

How can I control by which attribute the posts are ordered and displayed?

Upvotes: 0

Views: 361

Answers (1)

Kirti Thorat
Kirti Thorat

Reputation: 53038

In your controller's corresponding action to this view,

Set an instance variable ordered as per your requirement. For example:

def action_name
  ## ....
  @posts = @model_instance.posts.order(attrb: :desc)  
end

Where replace

  • @model_instance with the associated instance of model.
  • attrb with which you would like to order
  • desc for descending order or asc for ascending order

After this in your view, update your fields_for as below:

<%= f.fields_for @posts, :posts do |builder|  %>
  <%= render 'post_fields', builder: builder %>
<% end %>

Upvotes: 1

Related Questions