我正在尝试使用rails 4,acts_as_list gem和jQuery来对(scrape)所拥有的表中的项目(页面)进行排序。我认为我的问题可能在于控制器方法,任何帮助都会非常感激。排序在前端工作得很好,trs上下移动,就像railscast显示的那样。但它没有更新位置,刷新之后又回到原来的状态。
这是我的控制器方法排序
def sort
@scrape = Scrape.find(params[:scrape_id])
@pages = @scrape.pages
@pages.each_with_index do |id, index|
Page.where(position: id).update_all({position: index+1})
end
render nothing: true
end
这是我的观点
= form_for @scrape do |f|
%p
= f.label :url
= f.text_field :website
%table#pages
%tbody{"data-update-url" => sort_scrape_pages_url(@scrape)}
= f.fields_for :pages, @pages do |page_type|
= content_tag_for :tr, page_type.object do
%td=page_type.object.position
%td
= link_to page_type.object.url, scrape_page_path(@scrape, page_type.object.id)
%td
= page_type.collection_select :page_type, ["Service Page", "Homepage","About Us", "Contact Us", "Informational", "Sitemap", "Privacy Policy", "Terms", "Blog"], :to_s, :humanize
= f.submit "Submit"
这是我的jQuery:
jQuery ->
$('#pages tbody').sortable
axis: 'y'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
这就是我的控制台所说的发生的事情,如果这对任何人都有帮助,我就不会这样做。
Started POST "/scrapes/3/pages/sort" for 127.0.0.1 at 2015-04-19 18:28:56 -0700
Processing by PagesController#sort as */*
Parameters: {"page"=>["18", "17", "19", "20", "21", "22", "23", "24"], "scrape
_pages_attributes_0"=>["id"], "scrape_pages_attributes_1"=>["id"], "scrape_pages
_attributes_2"=>["id"], "scrape_pages_attributes_3"=>["id"], "scrape_pages_attri
butes_4"=>["id"], "scrape_pages_attributes_5"=>["id"], "scrape_pages_attributes_
6"=>["id"], "scrape_pages_attributes_7"=>["id"], "scrape_id"=>"3"}
Scrape Load (1.0ms) SELECT "scrapes".* FROM "scrapes" WHERE "scrapes"."id" =
$1 LIMIT 1 [["id", "3"]]
Page Load (1.0ms) SELECT "pages".* FROM "pages" WHERE "pages"."scrape_id" = $
1 ORDER BY position ASC [["scrape_id", 3]]
SQL (2.0ms) UPDATE "pages" SET "position" = 1 WHERE "pages"."id" = 17
SQL (1.0ms) UPDATE "pages" SET "position" = 2 WHERE "pages"."id" = 18
SQL (0.0ms) UPDATE "pages" SET "position" = 3 WHERE "pages"."id" = 19
SQL (0.0ms) UPDATE "pages" SET "position" = 4 WHERE "pages"."id" = 20
SQL (0.0ms) UPDATE "pages" SET "position" = 5 WHERE "pages"."id" = 21
SQL (0.0ms) UPDATE "pages" SET "position" = 6 WHERE "pages"."id" = 22
SQL (1.0ms) UPDATE "pages" SET "position" = 7 WHERE "pages"."id" = 23
SQL (0.0ms) UPDATE "pages" SET "position" = 8 WHERE "pages"."id" = 24
Rendered text template (0.0ms)
Completed 200 OK in 15ms (Views: 0.0ms | ActiveRecord: 6.0ms)
答案 0 :(得分:1)
您正在通过ID找到错误的位置,但您需要找到按ID记录
所以你的方法,你需要替换你的代码
@pages.each_with_index do |id, index|
Page.where(id: id).update_all(position: index + 1)
end
答案 1 :(得分:0)
错误发生在我的控制器中。我的工作排序方法如下。
def sort
params[:page].each_with_index do |id, index|
Page.where(id: id).update_all(position: index + 1)
end
render nothing: true
end