假设我有:包含许多问题的“调查”,其中有许多“答案”
如果我有一个“调查”,其中有两个例子的“问题”,让我们称之为:“好问题”和“坏问题”
“好问题”有5个‘答案’,‘坏问题’有3个‘答案’
如果“好问题”和“坏问题”与jQuery交互连接到了可排序列表中。http://jqueryui.com/sortable/#connect-lists
我知道如何使用jQuery将它们显示为2个可排序的列表,我还可以将“答案”从“坏问题”删除到“好问题”。但是,我如何将他们的新排序位置和他们新排序的关联保存到另一个“问题”回Rails数据库?
Railscast有如何保存单个可排序列表的位置,但不保存属于不同关联模型的列表的位置。http://railscasts.com/episodes/147-sortable-lists-revised
我真的很感激你们的帮助!
编辑
我意识到,我只需要向Rails控制器发布一个元素id,我就把“答案”放到其中(即<ol class = "connectableSortable" id = "Good_Question"</ol>
)。
这是Railscast如何将POST传递给Rails控制器以排序顺序传递object_id数组的语法。
jQuery ->
$('#faqs').sortable(
axis: 'y'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
)
我如何更新这个帖子,将列表ID传递给它,这样我就可以更新它所属的列表'ID‘的’答案‘外键了?
这个答案有一种检索列表ID. Get the item/object where the element is dropped的方法。
所以现在,我真的需要知道如何将一个额外的参数返回给rails控制器。有什么帮助吗?
发布于 2012-11-05 16:52:51
经过几天的努力,我终于找到了自己想要的东西。这里的模式是一天有很多活动(相对于最初的问题,一个问题有很多答案)。
这是我的jQuery代码(在Coffeescript中):使用jQuery选择器获取每个列表项的ID和每个列表项的列ID。将其作为类似于此Activity:[{"id":"1", "column":"1"}, {"id":"2", "column":"1"}...etc]
的参数推送
jQuery ->
$('[id*="day"]').sortable(
connectWith: ".day"
placeholder: "ui-state-highlight"
update: (event, ui) ->
neworder = new Array()
$(this).children().each ->
column = $(this).parent().attr("id").match(/\d+/)[0]
id = $(this).attr("id").match(/\d+/)[0]
neworder.push(
id: id
column: column
)
alert neworder
$.ajax
url: "sort"
type: "POST"
data: { Activity: JSON.stringify(neworder) }
).disableSelection()
如何解析AJAX对Rails控制器的调用:我正在遍历数组中的每个{"id":"1", "column":"1"}
对象,并获得它的索引位置。
def sort
JSON.parse(params[:Activity]).each_with_index do |x, index|
idx = x["id"]
positionx = index+1
column = x["column"]
activity = Activity.find(idx)
activity.update_attributes(:position => positionx, :day_id => column)
end
render nothing: true
end
回到我的模型中,我根据它的位置来排序“活动”关联,所以当我在视图中列出它时,它会出现在正确的位置上。
class Day < ActiveRecord::Base
has_many :activities, :order => 'position'
accepts_nested_attributes_for :activities, allow_destroy: true
end
在以下两个答案中,我更详细地介绍了我是如何做到这一点的:
Formatting Parameters for Ajax POST request to Rails Controller - for jQuery-UI sortable list
https://stackoverflow.com/questions/13204628
复制相似问题