索引视图中的 Rails3 更新布尔复选框 [英] Rails3 Update Boolean Checkbox from Index View

查看:31
本文介绍了索引视图中的 Rails3 更新布尔复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们公司构建一个简单的任务应用程序,作为订购系统的一部分.

我有一个包含许多规则的任务列表.没什么复杂的......我坚持的是添加一个复选框来完成任务.我希望它在索引视图中实时完成,而无需点击提交..

我真的不知道在哪里看.我想我需要使用 ajax 来做到这一点 - 任何人都可以推荐一个教程或告诉我我应该寻找什么.

还想过一个插件,比如就地编辑.

提前致谢

--- 编辑 1 --

根据下面@pcg79 的建议,我已将以下内容添加到我的应用程序中,但我不明白我实际上是如何更改状态的.

在我的索引视图中,我有这个:

<%= check_box_tag 'complete_task_1', '', false, { 'data-href' =>任务路径(@task) } %><

我已将以下内容添加到我的 application.js(添加了 # 以使其正确调用)

 $('#complete_task_1').click(function() {$.ajax({url: $(this).data('href'),类型:'PUT',数据类型:'html',成功:功能(数据,文本状态,jqXHR){//在这里做一些事情,比如设置一个 flash msg}});});

由于缺乏理解,我将其添加到我的任务控制器中:

def 完成@task = Task.find(params[:id])@task.status = 真结尾

这看起来很合理,但不确定如何在 ajax 中实际调用它?

在我的开发日志中,我可以看到它有点工作,但它说:

ActionController::RoutingError(没有路由匹配/tasks"):

-- 编辑 2 --

根据下面@jdc 的建议,我尝试将以下内容添加到 routes.rb:

get 'tasks/:id/completed' => 'tasks#completed', :as => :completed_task

但仍然得到 RoutingError.

-- 轻微更新--

根据下面@pcg79 的出色建议,我已使用以下内容更新了我的文件.

Routes.rb

<块引用>

get 'task/:id' => 'tasks#completed', :as => :completed_task

Index.html.erb

<%= check_box_tag 'complete_task_1', '', false, { 'data-href' =>Completed_task_path(:id => task.id) } %></td>

任务控制器

def 完成@task = Task.find(params[:id])@task.status = 真@task.save结尾

我的浏览器没有出现错误,但我的开发日志显示:

ActionController::RoutingError(没有路由匹配/tasks"):

对于一个简单的复选框来说,这是一项艰巨的工作!!!

-- 另一个更新--

玩了一整天后,我决定看看用 button_to 会发生什么,忘记了 ajax 方面的事情.我把它放在我的代码中:

<%= button_to "Complete", completed_task_path(task.id) %>

并将路线更改为:

match 'tasks/:id/completed' =>'tasks#completed', :as =>:已完成_任务

这是一种享受.改回 check_box_tag 再次打破一切:(

几乎确定这是我的函数的内容.删除了一些代码后,我可以更新 #:

的 css

 $('#complete_task_1').click(function() {$.ajax({成功:功能(数据,文本状态,jqXHR){$('#thing').css("颜色","红色");}});});

知道我需要什么来调用我的操作吗?J

解决方案

如果我明白你在找什么(当复选框被选中或取消选中时,一个 Ajax 请求被发送到服务器,并且关联的对象与复选框的结果),那么是的,您需要在 Ajax 中执行此操作.

对于 Rails 3,您可能正在使用 jQuery(或者,IMO,您应该使用).您需要在复选框元素上实现点击事件.当它被触发时,点击事件将对您的服务器进行 Ajax 调用.你会想要做一个 PUT 请求,因为它是一个更新.您将发送对象的 id 和复选框的值.

有相当多的站点提供了 Rails 和 Ajax 的示例.这个(http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/) 很好,因为它让您使用 HTML 5数据"字段我喜欢.SO上也有很多类似的问题.这是一个不是 Rails 但会让你了解如何编写 jQuery 的想法(AJAX 复选框).>

编辑以在评论中回答问题

复选框可以放在任何你想要的地方,因为你在做 Ajax.如果你想在你的索引视图中使用它,那就是你把它放的地方.你的复选框看起来像这样(请理解我没有仔细检查我的语法或任何东西):

= check_box_tag 'complete_task_1', '', false, { 'data-href' =>任务路径(@task_1)}

那么你的 jQuery 将类似于:

$('complete_task_1').click(function() {$.ajax({url: $(this).data('href'),类型:'PUT',数据类型:'html',成功:功能(数据,文本状态,jqXHR){//在这里做一些事情,比如设置一个 flash msg}});});

第二次我意识到我忘记在 Ajax 中实际发送复选框的值.您可以这样做,只需调用 @task.update_attributes 或者您可以使 url 成为仅完成任务的特定方法.

编辑更新的问题:

解释一下我的第二次编辑,为了更新要完成的任务,你可以做两件事之一.您可以调用专门用于设置 status 属性的方法.或者,您可以调用普通的 RESTful update 方法,传入 :task =>{:状态=>true} 并调用 @task.update_attributes(params[:task]).你选择了前者,IMO,这很好.

所以你有两个问题.首先是您没有引用指向您的 completed 方法的新路线.第二个是你没有在 completed 方法中保存你的对象.

要解决第一个问题,您需要更改check_box_tag 方法中的data-href 属性指向的路径.您不想要 task_path.IIRC,你会想要completed_task_path(@task).找出路径名称的最简单方法是在 Rails 项目的根目录中运行 rake routes.

要解决第二个问题,只需确保最后调用 @task.save.

def 完成@task = Task.find(params[:id])@task.status = 真@task.save结尾

I'm building a simple tasks application for our company as part of an ordering system.

I have a list of tasks with a number of rules. Nothing complex... What I'm stuck on is the addition of a checkbox to complete the task. I want it done live, from the index view without having to hit submit..

Am really not sure even where to look. I figure I need to use ajax to do this - can anyone recommend a tutorial or tell me what I should be looking for.

Have also thought about a plugin, like the edit in place ones out there.

Thanks in advance

--- EDIT 1 --

Following advice from @pcg79 below, I've added the following to my application but am not understanding how I go out actually changing the status.

In my index view I have this:

<%= check_box_tag 'complete_task_1', '', false, { 'data-href' => tasks_path(@task) } %><

I've added the following to my application.js (added a # to get it to call properly)

 $('#complete_task_1').click(function() {
  $.ajax({
    url: $(this).data('href'),
    type: 'PUT',
    dataType: 'html',
    success: function(data, textStatus, jqXHR) {
      // Do something here like set a flash msg
    }
  });
});

For lack of understanding, I added this to my tasks controller:

def completed 
    @task = Task.find(params[:id])
    @task.status = true
 end

Which seemed reasonable but wasn't sure how to actually call that in the ajax?

In my development log I can see it sort of working but it says this:

ActionController::RoutingError (No route matches "/tasks"):

-- EDIT 2 --

As per advice from @jdc below, I've tried adding the following to routes.rb:

get 'tasks/:id/completed' => 'tasks#completed', :as => :completed_task

But still get the RoutingError.

-- Slight Update --

Following the excellent advise from @pcg79 below, I've updated my files with the following.

Routes.rb

get 'task/:id' => 'tasks#completed', :as => :completed_task

Index.html.erb

<td><%= check_box_tag 'complete_task_1', '', false, { 'data-href' => completed_task_path(:id => task.id) } %></td>

Tasks controller

def completed 
    @task = Task.find(params[:id])
    @task.status = true
    @task.save
  end

I get no errors in my browser, but my development log shows this:

ActionController::RoutingError (No route matches "/tasks"):

For a simple checkbox, this is hard work!!!

-- Another update --

Having played all day, I decided to see what would happen with a button_to instead, forgetting the ajax side of things. I put this in my code:

<%= button_to "Complete", completed_task_path(task.id) %>

And changed routes to:

match 'tasks/:id/completed' => 'tasks#completed', :as => :completed_task

Which worked a treat. Changing back to check_box_tag breaks it all again :(

Pretty much worked out it's the contents of my function. Having removed some code, I can update the css for a #:

 $('#complete_task_1').click(function() {
  $.ajax({
    success: function(data, textStatus, jqXHR) {
        $('#thing').css("color","red");
    }
  });
});

Any idea what I'd need to call my action?? J

解决方案

If I understand what you're looking for (when the checkbox is checked or unchecked an Ajax request is sent to the server and the associated object is saved with the result of the checkbox), then yes you'll want to do it in Ajax.

With Rails 3 you're probably using jQuery (or, IMO, you should be). You'll need to implement a click event on the checkbox element. That click event, when it's fired, will do an Ajax call to your server. You'll want to do a PUT request since it's an update. You'll send the id of the object and the value of the checkbox.

There are a decent amount of sites that have examples of Rails and Ajax. This one (http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/) is good as it has you use the HTML 5 "data" fields which I like. There's also a bunch of similar questions here on SO. Here's one that's not Rails but will give you an idea of how to write the jQuery (AJAX Checkboxes).

Edit to answer question in comment

The checkbox can be wherever you want it since you're doing Ajax. If you want it on your index view, that's where you put it. Your checkbox will look something like this (please understand I'm not double checking my syntax or anything):

= check_box_tag 'complete_task_1', '', false, { 'data-href' => task_path(@task_1) }

Then your jQuery will look something like:

$('complete_task_1').click(function() {
  $.ajax({
    url: $(this).data('href'),
    type: 'PUT',
    dataType: 'html',
    success: function(data, textStatus, jqXHR) {
      // Do something here like set a flash msg
    }
  });
});

Second edit: I realized I forgot to actually send the value of the checkbox in the Ajax. You can do that and just call @task.update_attributes or you can make the url a specific method that only completes tasks.

Edit for updated question:

To explain my second edit, in order to update the task to be completed, you can do one of two things. You can either call a method that is expressly for setting the status attribute. Or you can call your normal, RESTful update method passing in :task => {:status => true} and call @task.update_attributes(params[:task]). You've chosen to do the former which, IMO, is fine.

So you have two problems. The first is that you aren't referencing the new route which points to your completed method. The second is that you aren't saving your object in the completed method.

To fix the first problem, you need to change the path your data-href attribute in the check_box_tag method points to. You don't want task_path. IIRC, you'll want completed_task_path(@task). The easiest way to find out the name of the path is to run rake routes in your Rails project's root directory.

To fix the second problem, just make sure to call @task.save at the end.

def completed 
  @task = Task.find(params[:id])
  @task.status = true
  @task.save
end

这篇关于索引视图中的 Rails3 更新布尔复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆