在rails窗体中维护数组的顺序 [英] Maintain the order of an array in rails forms

查看:216
本文介绍了在rails窗体中维护数组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个模型(Workout,WorkoutSet,WorkoutStep)和以下关联:


  • 锻炼有很多套

  • 一个WorkoutSet有许多WorkoutSep

  • 而一个WorkoutStep有一组视频(称为 video_usage [] ))



使用simple_form和cocoon我让表单编辑这些关联,但是在最深层次(WorkoutStep的视频数组)当我编辑锻炼时,顺序看起来并不是恒定的,相反,最后一次属性被修改(在这种情况下,修改是改变一个属性,比如选择另一个视频),排序(猜测)。



我希望视频数组在编辑时保持不变。



这就是我的表单的样子:

_workout_sets_fields.html.haml

  .nested-fields 
= f.simple_fields_for:main_video_usage do | mv |
=渲染'main_video_usage_fields',f:mv
.steps {:style => margin-left:680px}
= link_to_remove_association'remove step',f
= link_to_add_association'add video',f::main_video_usage

_main_video_usage_fields.html.haml

  .nested-fields 
= f.collection_select:video_id,Video.all.order(:title),:id,:title


解决方案

您可以给出明确的顺序,使用 id created_at 如果您想保留创建顺序:

  has_many:main_video_usage, - > {order('id asc')},class_name:'VideoUsage :: Main',as::parent 


I have 3 models (Workout, WorkoutSet, WorkoutStep) with the following associations:

  • A Workout has many sets
  • A WorkoutSet has many WorkoutSep
  • And a WorkoutStep has an array of videos (called video_usage[])

Using simple_form and cocoon I made the forms to edit such associations but, at the deepest level (the array of videos of WorkoutStep) by the time I edit a Workout, the order seem not to be constant, being, instead, ordered by (guessing) the last time the attribute has been modified (in this case, modified is changing a property, such as selecting another video).

I want the array of videos to remain constant between edits.

This is how my form looks like:

_workout_sets_fields.html.haml

.nested-fields
  = f.simple_fields_for :main_video_usage do |mv|
    = render 'main_video_usage_fields', f: mv
  .steps{ :style => "margin-left: 680px" }
    = link_to_remove_association 'remove step', f
    = link_to_add_association 'add video', f, :main_video_usage

_main_video_usage_fields.html.haml

.nested-fields
  = f.collection_select :video_id, Video.all.order(:title), :id, :title

解决方案

You can give an explicit order, use id or created_at if you want to keep the order of creation:

has_many :main_video_usage, -> { order('id asc') }, class_name: 'VideoUsage::Main', as: :parent

这篇关于在rails窗体中维护数组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆