获取jQuery sortable connectWith serialize方法的关联id

时间:2012-04-18 02:27:30

标签: jquery ruby-on-rails-3 jquery-ui

使用Rails 3。

状态表中的模型:

id
country_id
position
created_at
updated_at

使用Javascript:

$(".sortable_country").sortable({
    connectWith: ".sortable_country",
    update: function() {
        console.log($(this).sortable("serialize"));
    }
});

HTML:

<strong>Country 1</strong>
<ul id="country_1" class="sortable_country">
    <li id="state_1">
        State 1
    </li>
    <li id="state_2">
        State 2
    </li>
    <li id="state_3">
        State 3
    </li>
    <li id="state_4">
        State 4
    </li>
</ul>
<strong>Country 2</strong>
<ul id="country_2" class="sortable_country">
    <li id="state_5">
        State 5
    </li>
    <li id="state_6">
        State 6
    </li>
    <li id="state_7">
        State 7
    </li>
    <li id="state_8">
        State 8
    </li>
</ul>

spots_controller.rb:

def sort
  params[:states].each_with_index do |id, index|
    State.update_all([&rsquo;position=?&rsquo;, index+1], [&rsquo;id=?&rsquo;, id])
  end
  render :nothing => true
end

请忽略其他必需的代码,因为我已经简化了代码以进行故障排除。在此示例中,我将State 5排序为Country 1列表。排序后,返回序列化结果为:

state[]=6&state[]=7&state[]=8
state[]=1&state[]=2&state[]=3&state[]=5&state[]=4

如何在序列化结果中包含关联的country_id,以便我的应用可以State 5 country_id 12,{{1}}在排序之前?

谢谢。

1 个答案:

答案 0 :(得分:1)

将其放在.sortable()

update: function() {
    $.post($(this).data('update-url'), $(this).sortable('serialize'))
    .error(function() { 
    alert("Sorry, could not save the positions. Please refresh this page.");
    })
}

相关的ID将在排序后自动发布到单个帖子中。