Limit simple_form_for associated records number in Ruby on Rails

牧云@^-^@ 提交于 2020-01-07 03:39:08

问题


I have a large psychological test of 251 question. Each user can complete that test many times. So I created Summary model to represent each completion. Each Summary has many Answers. For each Summary I created a form that represents collection of answers, using Slim templater and simple_form gem:

= simple_form_for(@summary) do |f|
  = f.simple_fields_for :answers do |a|
    .question
      = a.input :question_id, as: :hidden
      div= a.object.question.title
      - if a.object.question.kind_of? SpiritualityQuestion
        ol class="sortable"
          - a.object.question.sortable_variants.each do |sortable_variant|
            = content_tag_for :li, sortable_variant
              = sortable_variant.title
        = a.input :text_data, as: :hidden, input_html: { class: 'sortable_data' }
      - elsif a.object.question.kind_of? MultilineQuestion
        div Time remaining: <span class="time">60</span> s.
        = button_tag 'Start', type: 'button', class: 'start_button btn btn-primary'
        = a.input :text_data, label: false, input_html: { class: 'span8 timed_text', cols: '60', rows: '20', disabled: true }
      - else
        = a.association :variant, collection: a.object.question.variants, as: :radio, label: false
    br
  = f.input :user_id, as: :hidden
  = f.input :psy_test_id, as: :hidden

  .actions
    = f.button :submit, value: 'Save', class: 'btn btn-large btn-success'

And I have related controller action:

@summary = Summary.where(completed: false, user: current_user, psy_test: PsyTest.first)
                  .includes(:answers => { :question => :variants })
                  .first_or_initialize
@summary.build_answers if @summary.new_record?

Summary.build_answers:

def build_answers
  # Creating answers for questions
  psy_test.questions.includes(:variants).each do |q|
    answers.new(question: q)
  end
end

Now I'm trying to make the test to be paginated, because it's very large and the form generates very slowly. So I want to add limit and offset to answers. Something like that:

= f.simple_fields_for answers.limit(@limit).offset(@offset) do |a|

How it can be made?


回答1:


I've looked to do field_for source and found simple answer, which I wasn't able find in any guide:

= f.simple_fields_for :answers, @summary.answers.limit(@limit).offset(@offset) do |a|


来源:https://stackoverflow.com/questions/18917565/limit-simple-form-for-associated-records-number-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!