Search code examples
ruby-on-railsrubymodel-view-controllercheckboxmodels

Ruby on Rails: updating model when checkbox is changed


I got projects and todos inside them, todos have checkbox & text, so when I change the checkbox the whole model must be updated without any buttons.

Here is my project on heroku: https://polar-scrubland-30279.herokuapp.com/

index.html.erb ( I know that I'm not the best code speller)

<% @projects.each do |project| %>
  <div class="col-md-4">

    <div class="project">
      <%= form_for(local_assigns[:project] || project) do |f| %>

        <div class="project-header">
          <h2> <%= f.object.title %> </h2>
        </div>

        <div class="project-todos">
          <%= f.fields_for(:todos) do |tf| %>
            <div class="todo">
              <div class="todo--checkbox">
                <%= tf.check_box :isCompleted %>
              </div>
              <div class="todo--text">
                <%= tf.object.text %>
              </div>
            </div>
          <% end %>
        </div>
      <% end %>
    </div>

  </div>
<% end %>

This is my ProjectsController:

class ProjectsController < ApplicationController

  def index
    @projects = Project.all
  end

  def show
    @project = Project.find(params[:id])
  end

  def new
    @project = Project.new
  end

  def create
    @project = Project.new(project_params)
    if @project.save
      # ...
    else
      # ...
    end
  end

  def update
    if @project.update(project_params)
      # ...
    else
      # ...
    end
  end

  private

  def set_project
    @project = Project.find(params[:id])
  end

  def project_params
    params.require(:project).permit(:foo, :bar, todos_attributes: [:isCompleted, :text])
  end

end

project.rb

class Project < ActiveRecord::Base
  has_many :todos
  accepts_nested_attributes_for :todos
end

todo.rb

class Todo < ActiveRecord::Base
  belongs_to :project
end

The question is: how do I connect my form with my controller, and change todo's boolean variable when checkbox is checked/uncheked. I've tried some variants, but there is need a refresh button, which I don't wanna have.

GitHub - https://github.com/NanoBreaker/taskmanager


Solution

  • You have to use jQuery checkbox change and click event to catch checkbox change event,

    further you can use ajax request http://api.jquery.com/jquery.ajax/ on the change event,

    in the ajax request use path to update method in Projects controller.

    Note that you have to put the path in file config/routes.rb, something like this:

    post 'url' => 'projects#update'