Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aliibrahim/7154cf4cc470dd8fb151d6f97b71a7ad to your computer and use it in GitHub Desktop.
Save aliibrahim/7154cf4cc470dd8fb151d6f97b71a7ad to your computer and use it in GitHub Desktop.
class TodoListsController < ApplicationController
before_action :set_current_user
before_action :set_todo_list, only: %i[show complete_item]
ORDER_OPTIONS = ['created_at', 'updated_at']
def index
sort_order = (params[:asc] == 'false') ? 'ASC' : 'DESC'
@lists = @user.todo_lists.order("#{sort_by_field} #{sort_order}")
end
def show
end
# Mark an item as done and return user back from whence they came!
def complete_item
@list.complete!
redirect_to :back
end
def new
@list = TodoList.new
end
def create
@list = @user.todo_lists.build(todo_list_params)
if @list.save!
redirect_to todo_lists_url
else
flash[:notice] = "Error saving list"
redirect_to new_todo_list_url
end
end
private
def set_current_user
@user ||= User.find(session[:user_id])
end
def set_todo_list
@list = @user.todo_lists.find(params[:id])
end
def sort_by_field
sort_field = params[:sort] if params[:sort] && ORDER_OPTIONS.include?(params[:sort])
sort_field ||= 'created_at'
sort_field
end
def todo_list_params
params.require(:todo_list).permit(
:title,
:done
)
end
end
module TodoListsHelper
def formatted_title(list)
list.title + (list.todo_items.empty? ' (Complete)' : '')
end
end
class TodoItem < ApplicationRecord
scope :uncompleted, -> { where(done: 'false') }
belongs_to :todo_list
validates :title, presence: true
# Completes to do item, saving to database.
def complete!
update!(done: true)
end
end
class TodoList < ApplicationRecord
has_many :todo_items
belongs_to :user
end
class User < ApplicationRecord
has_many :todo_lists
end
<%-# Display the current user's lists along with any uncompleted items -%>
<% @lists.each do |list| %>
<h2><%= formatted_title(list) %></h2>
<ul>
<% list.todo_items.uncompleted.each do |item| %>
<li><% item.title %> - <%= link_to "Done!", complete_item_todo_lists(item), method: :put %></li>
<% end %>
</ul>
<% end %>
<h2><%= formatted_title(@list) %></h2>
<ul>
<% @list.todo_items.uncompleted.each do |item| %>
<li><% item.title %> - <%= link_to "Done!", complete_item_todo_lists(item), method: :put %></li>
<% end %>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment