我在编写控制器操作时遇到问题,该操作将Post ID作为参数传递,并在发布之前将它们按特定顺序排序。在Rails控制器中对项目进行排序控制器方法
的帖子具有position
属性(我使用用于分选acts_as_list),并且要么已发表或未发表(搜索与named_scopes Post.published
和Post.unpublished
,相应地)。
本质上说是一个JavaScript接口,使用户可以拖动未发表的文章到一个队列,通过将IDS作为post_ids
参数的控制方法,看起来像这样把它们发布:
def publish
Post.update_all(['published=?', true], :id => params[:post_ids])
redirect_to admin_path
end
出版像这样的职位工作正常。接下来我需要做的是按照特定顺序排列帖子的位置,这就是我遇到问题的地方。
比方说,用户拖动5后,然后张贴3,然后张贴到队列中,并点击“发布”。
然后我想要做的就是组织所有的帖子在第一个位置按顺序排列5,3,7,然后按照他们已经在的顺序排列Post对象的其余部分,这样Post.position排序将[5, 3, 7, ...the rest of the posts in order here...]
然后如果用户拖动两个新的职位到队列中,单击“发布”(这时候让我们说帖2和4),该职位应在订货[2, 4, 5, 3, 7, ...the rest of the posts in order here...]
那么对于最后一个例子,假设用户将帖子10,1和12移动到队列中并发布,订单应该是[10, 1, 12, 2, 4, 5, 3, 7, ...the rest of the posts in order here...]
etc ...
我会显示我一直在处理的代码,但我不确定这会有帮助,因为我没有正确排序它。但本质上我想这是一个需要两个数组的问题,第一个是所有Posts,第二个是发布的帖子,并将Posts中的每个项目发布到所有Posts数组的开头,然后发布。我似乎无法得到它的工作。任何帮助在这里将不胜感激,我感谢您提前为您的时间!
编辑 如果有帮助,这是我迄今为止编写的代码。在测试中,似乎这种方法第一次正确地对队列中的帖子进行排序,但是任何后续发布的帖子都不会移动到发布的帖子列表的前面。
def publish
if params[:to_publish].present?
# :to_publish are the posts dragged into the queue in order.
# Here I'm cleaning up the Javascript input and then iterating
# through them to update their sort order.
params[:to_publish].to_s.split(",").uniq!.each_with_index do |id, index|
Post.update_all(['position=?', index + 1], ['id=?', id])
end
end
# :post_ids are the posts to be published, order is irrelevant.
# For client-side reasons they're passed as a separate parameter.
Post.update_all(['published=?', true], :id => params[:post_ids])
redirect_to admin_path
end
是的,谢谢。这hacky分裂和uniq!行只是一个快速的解决方法,因为客户端目前存在一些sl JavaScript的JavaScript。当我清理JavaScript代码时,我不需要调用uniq!,但现在对于我来说这只是一个较低的优先级。再次感谢这个提示。 – btw 2010-08-29 18:33:01