Rails使用复选框更改对象

时间:2016-03-03 12:34:50

标签: ruby-on-rails

对象Task包含boolean字段complete。如何通过按复选框更改对象的状态?

任务模型:

class Task < ActiveRecord::Base
  belongs_to :project

  scope :complete, -> { where(done: true) }
  scope :incomplete, -> { where(done: nil) }

  def mark_complete!
    self.update_attribute(:done, true)
  end

end

任务控制器:

def done
    @task = Task.find(params[:id])
    @task.mark_complete!
  end

routes.rb中:

get '/done/:id', to: 'tasks#done', as: 'done'

done.js.erb: $('#row_<%= task.id %>').css("background-color", "yellow");

查看任务#_task.html.erb:

<tr id="row_<%= task.id %>" data-item-id=<%= "#{task.id}" %> class="item">
  <td><%= task.name %></td>
  <td><%= task.done %></td>
  <td><%= link_to "Mark Complete", done_path(task), remote: true %></td>
  <td><%= link_to '<i class="glyphicon glyphicon-trash"></i>'.html_safe, task_path(task), remote: true,
                  class: 'btn btn-xs',
                  method: :delete,
                  data: {confirm: 'Are you sure?'} %></td>
</tr>

2 个答案:

答案 0 :(得分:1)

你可以这样做:

的routes.rb

resources :tasks do
  collection do
    put :mark_complete
  end
end

tasks_controller.rb

def mark_complete
  task = Task.find(params[:task_id])

  if task.mark_complete!
    render json: task.done?, status: :ok
  else
    render json: task.errors, status: :unprocessable_entity
  end
end

task.html.erb

...

<td><%= link_to "Mark Complete", "javascript:void(0)", class: "mark-complete", data_task_id: task.id %></td>

...

<script>
  $(document).ready(function() {
    $(document).on('click', '.mark-complete', function() {
      var taskId = $(this).data('taskId');

      $.ajax({
        url: "#{mark_complete_tasks_path}",
        type: 'PUT',
        data: { task_id: taskId },
        success: function(response, status, xhr) {
          // Whatever you want to do here with the item that was marked complete.
        },
        error: function(xhr, status, error) {
          console.log(xhr, status, error);
        },
      });
    });
  });
</script>

答案 1 :(得分:0)

<强> routes.rb中:

resources :tasks do
    member do
      post 'done'
    end
  end

<强>控制器:

def done
    @task = Task.find(params[:id])
    @task.update_attributes(:done => params[:done])

    respond_to do |format|
      format.js {}
    end

  end

查看:

....
 <td><%= task.done %></td>
 <td><%= check_box_tag 'done', task.id , task.done, :class => "task-check", remote: true %></td>
....

<script>
  $(".task-check").bind('change', function(){
    $.ajax({
      url: '/tasks/'+this.value+'/done',
      type: 'POST',
      data: {"done": this.checked},
    });
  });

</script>

任务#done.js.erb: window.location.reload();