rforte
rforte

Reputation: 1167

sorting accepts_nested_attributes_for in formtastic

I am trying to use formtastic to render a nested form. I have has_many/accepts_nested_attributes_for setup in my parent model. Everything is working great. The only issue is that I want to sort the order of the nested model.

# this works but i want answers sorted a certain way
= semantic_form_for survey do |f|
  = f.inputs :for => :answers do |answer_form|
    = answer_form.input :content

If I try doing something like:

# form styles become extremely messed up but the order is correct
= semantic_form_for survey, do |f|
  = f.semantic_fields_for :answers, f.object.answers.joins(:question).order('questions.position') do |answer_form|
    = answer_form.input :content

I've even tried creating a 'fake' has_many relationship called :sorted_answers using :finder_sql and :class but that doesn't work either (answer_form is nil IIRC).

I guess what I'm asking is if I can use :for => (relationship) but specify the ordering of the relationship. Maybe using :for_options?

Upvotes: 1

Views: 616

Answers (2)

Vic
Vic

Reputation: 1552

using formtastic 3.1.3, this worked for me

f.input :answers, as: :check_boxes, :member_label => :some_column, collection: Answer.order(:some_column)

Thing to take note is that the collection has to be of a ActiveRecord_Relation class and not array since Formtastic is activerecord-ish

Upvotes: 0

brookz
brookz

Reputation: 497

I met the same condition of you ,here is my solution:

You should have a model named "Answer", set the order in default_scope:

class Answer < ActiveRecord::Base

  default_scope :order => "id"

end

Upvotes: 1

Related Questions