RubyOnRails 2.2 + Jquery UI 可排序& AJAX:我就是这么做的。 有没有更好的办法?

发布于 2024-07-11 18:18:16 字数 4551 浏览 10 评论 0原文

在 Rails 2.2 项目中,我让用户将项目列表放在一个组合对象中(即:PortfolioHasManyProjects)。 页面上有一个用于常规文本、标题等的 Rails 表单,以及 2 个可排序列表; 这些列表用于将项目从全局项目列表拖到您的投资组合项目列表中。

它与这里所做的类似: http://ui.jquery.com/latest/demos/function/# ui.sortable

我的投资组合列表 (#drag_list) 会根据更改进行更新,并通过 AJAX 调用提交其​​序列化数据。 这是在 application.js 文件中完成的:

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitDragWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $("#drag_list").sortable('serialize'), null, "script");
    return false;
  })
  return this;
};

$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});


/-------------------------------------------/

$(document).ready(function(){

    $(".ajax_drag").submitDragWithAjax();

    $("#drag_list").sortable({
        placeholder: "ui-selected",
        revert: true,
        connectWith:["#add_list"],
        update : function () {
            $("#drag_list").submit();
        }
    });

    $("#add_list").sortable({ 
        placeholder: "ui-selected",
        revert: true,
        connectWith:["#drag_list"]
    });

这就是事情变得棘手的地方。 我不确定如何处理序列化数据并将其与表单一起提交到 new.html.erb 文件中的控制器。 所以我所做的就是让 new.js.erb 将隐藏的表单字段插入到 new.html.erb 中,并包含我在控制器中提取的数据。

这是 new.js.erb:

$("#projects").html("");
<% r = params[:proj] %>
<% order=1 %>
<% for i in r %>
  $("#projects").append("<input type=hidden name=proj[<%=order%>] value=<%=i%> />");
  <% order=order+1 %>
<% end %>

编辑 new.html.erb:

<h1>New portfolio</h1>
<h2>The List</h2>

<div class="list_box">
  <h3>All Available Projects</h3>
  <%= render :partial => "projects/add_list" %>
</div>

<div class="list_box">
  <h3>Projects currently in your new portfolio</h3>
  <%= render :partial => "projects/drag_list" %>
</div>

<div style="clear:both"></div>
<br/>
<br/>

<h2>Portfolio details</h2>
<% form_for(@portfolio) do |f| %>
  <%= f.error_messages %>
  <h3>Portfolio Name</h3>
  <p>
    <%= f.text_field :name %>
  </p>
  <h3>URL</h3>
  <p>
    <%= f.text_field :url %>
  </p>
  <h3>Details</h3>
  <p>
    <%= f.text_area :details %>
  </p>
  <p>

    <div id="projects">
    <input type="hidden" name="proj" value="" />   
    </div>

    <%= f.submit "Create" %>
  </p>
<% end %>

然后表单提交到投资组合控制器中的创建方法:

  def new
    @projects = Project.find(:all)
    @portfolio = Portfolio.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @portfolio }
      format.js
    end
  end




 def create
    @portfolio = Portfolio.new(params[:portfolio])
    proj_ids = params[:proj]
    @portfolio.projects = []
    @portfolio.save

    proj_ids.each {|key, value| puts "Key:#{key} , Value:#{value} " }
    proj_ids.each_value {|value| @portfolio.projects << Project.find_by_id(value) }

    respond_to do |format|
      if @portfolio.save
        flash[:notice] = 'Portfolio was successfully created.'
        format.html {  render :action => "index" }
        format.xml  { render :xml => @portfolio, :status => :created, :location => @portfolio }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @portfolio.errors, :status => :unprocessable_entity }
      end
    end
  end

所以最后是我的问题:

  1. 这是这样做的正确方法吗? 出于某种原因,我觉得事实并非如此,主要是因为在 Rails 中做其他所有事情似乎更加容易和直观。 这可行,但实现起来却很困难。 必须有一种更优雅的方式通过 AJAX 调用将序列化数据发送到控制器。

  2. 如何在同一页面上调用不同的 AJAX 操作? 假设我有一个可排序和自动完成 AJAX 调用,我可以有一个 sortable.js.erbautocomplete.js.erb 并从任何文件调用它们吗? 我不确定如何设置控制器来响应此问题。

In a Rails 2.2 project, I'm having users put together a list of projects into a portfolio object (i.e.: PortfolioHasManyProjects). On the page is a Rails form for regular text, titles etc., as well as 2 sortable lists; the lists are used for dragging projects from the global-project-list into your portfolio-project-list.

It is similar to what's done here:
http://ui.jquery.com/latest/demos/functional/#ui.sortable.

I have the portfolio list (#drag_list) updating on change and submitting its serialized data through an AJAX call.
This is done in the application.js file:

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitDragWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $("#drag_list").sortable('serialize'), null, "script");
    return false;
  })
  return this;
};

$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});


/-------------------------------------------/

$(document).ready(function(){

    $(".ajax_drag").submitDragWithAjax();

    $("#drag_list").sortable({
        placeholder: "ui-selected",
        revert: true,
        connectWith:["#add_list"],
        update : function () {
            $("#drag_list").submit();
        }
    });

    $("#add_list").sortable({ 
        placeholder: "ui-selected",
        revert: true,
        connectWith:["#drag_list"]
    });

Here is where things got tricky. I wasn't sure how to deal with the serialized data and have it submit with the form to the controller in the new.html.erb file. So what I did was have the new.js.erb insert hidden form fields into new.html.erb with the data that I would extract in the controller.

here's the new.js.erb:

$("#projects").html("");
<% r = params[:proj] %>
<% order=1 %>
<% for i in r %>
  $("#projects").append("<input type=hidden name=proj[<%=order%>] value=<%=i%> />");
  <% order=order+1 %>
<% end %>

which edits new.html.erb:

<h1>New portfolio</h1>
<h2>The List</h2>

<div class="list_box">
  <h3>All Available Projects</h3>
  <%= render :partial => "projects/add_list" %>
</div>

<div class="list_box">
  <h3>Projects currently in your new portfolio</h3>
  <%= render :partial => "projects/drag_list" %>
</div>

<div style="clear:both"></div>
<br/>
<br/>

<h2>Portfolio details</h2>
<% form_for(@portfolio) do |f| %>
  <%= f.error_messages %>
  <h3>Portfolio Name</h3>
  <p>
    <%= f.text_field :name %>
  </p>
  <h3>URL</h3>
  <p>
    <%= f.text_field :url %>
  </p>
  <h3>Details</h3>
  <p>
    <%= f.text_area :details %>
  </p>
  <p>

    <div id="projects">
    <input type="hidden" name="proj" value="" />   
    </div>

    <%= f.submit "Create" %>
  </p>
<% end %>

The form then submits to the create method in the portfolio controller:

  def new
    @projects = Project.find(:all)
    @portfolio = Portfolio.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @portfolio }
      format.js
    end
  end




 def create
    @portfolio = Portfolio.new(params[:portfolio])
    proj_ids = params[:proj]
    @portfolio.projects = []
    @portfolio.save

    proj_ids.each {|key, value| puts "Key:#{key} , Value:#{value} " }
    proj_ids.each_value {|value| @portfolio.projects << Project.find_by_id(value) }

    respond_to do |format|
      if @portfolio.save
        flash[:notice] = 'Portfolio was successfully created.'
        format.html {  render :action => "index" }
        format.xml  { render :xml => @portfolio, :status => :created, :location => @portfolio }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @portfolio.errors, :status => :unprocessable_entity }
      end
    end
  end

So finally my question:

  1. Is this a proper way of doing this? For some reason I feel it isn't, mostly because doing everything else in Rails seemed so much easier and intuitive. This works, but it was hell to get it to. There has to be a more elegant way of sending serialized data to the controller through AJAX calls.

  2. How would I call for different AJAX actions on the same page? Let's say I had a sortable and an autocomplete AJAX call, could I have a sortable.js.erb and autocomplete.js.erb and call them from any file? I'm not sure how to setup the controllers to respond to this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

來不及說愛妳 2024-07-18 18:18:16

如果您使用 jQuery,这是一个不错的解决方案

来自链接的博客:

我刚刚为 Rails/jQuery 应用程序编写了一些可排序的代码,并想我会在博客中介绍它只需要很少的代码,以及我在后端使用的单个 MySQL 查询。

This is a nice solution if you are using jQuery.

From the linked blog:

I just wrote some sortable code for a Rails/jQuery app and figured I would blog just how little code it takes, and also the single MySQL query I used on the backend.

这是我的解决方案,基于 Silviu 提到的文章。 我正在对属于课程的部分进行排序,因此包含了 LessonID。

这是在视图中 - 我正在使用 HAML,因此您必须转换为 erb。

#sorter
- @lesson.parts.each do |part|
  %div[part] <- HAML rocks - this constructs a div <div id="the_part_id" class="part">
    = part_screenshot part, :tiny
    = part.swf_asset.filename

js 看起来像这样:

    $('#sorter').sortable({items:'.part', containment:'parent', axis:'y', update: function() {
  $.post('/admin/lessons/' + LessonId + '/parts/sort', '_method=post&authenticity_token='+ AUTH_TOKEN+'&'+$(this).sortable('serialize'));
  $('#sorter').effect("highlight");
}});

这是在 PartsController 中调用的方法:

def sort
load_lesson
part_positions = params[:part].to_a
@parts.each_with_index do |part, i|
  part.position = part_positions.index(part.id.to_s) + 1
  part.save
end
render :text => 'ok'

end

def load_lesson
@lesson = Lesson.find(params[:lesson_id])
@parts = @lesson.parts

end

它需要一些工作来向用户提供反馈,但这对我来说很有效。

Here's my solution that is based on the article mentioned by Silviu. I'm sorting parts that belong_to lessons, hence the inclusion of the lessonID.

This is in the view - I'm using HAML so you'll have to convert to erb.

#sorter
- @lesson.parts.each do |part|
  %div[part] <- HAML rocks - this constructs a div <div id="the_part_id" class="part">
    = part_screenshot part, :tiny
    = part.swf_asset.filename

The js looks like this:

    $('#sorter').sortable({items:'.part', containment:'parent', axis:'y', update: function() {
  $.post('/admin/lessons/' + LessonId + '/parts/sort', '_method=post&authenticity_token='+ AUTH_TOKEN+'&'+$(this).sortable('serialize'));
  $('#sorter').effect("highlight");
}});

and here is the method that is called in the PartsController:

def sort
load_lesson
part_positions = params[:part].to_a
@parts.each_with_index do |part, i|
  part.position = part_positions.index(part.id.to_s) + 1
  part.save
end
render :text => 'ok'

end

def load_lesson
@lesson = Lesson.find(params[:lesson_id])
@parts = @lesson.parts

end

It needs some work on giving feedback to the user, but does the trick for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文