I am trying to make it possible for the users of a web application I am building to create lists of objects that they have created.
For example, the user has a list of objects such as groceries which could be anything from apples to oranges to pop-tarts.
I would then like it to be possible for me to return all of the groceries added to the database by the user and create a list by selecting those that are supposed to be on their grocery list.
Preferably this would be in a style such that they could click check boxes for the ones they wanted and then click save to create a new list.
I have looked into belongs_to, has_many relationships and tried creating a list object which has many groceries, but I can not figure out the form part of this strategy. I would appreciate any/all advice. Thanks!
Here is the code I have currently, I originally omitted it because I do not think I am on the right path, but here it is anyway just in case/provide more context:
Grocery Model:
class Item < ApplicationRecord
belongs_to :list, optional: true
end
List Model
class List < ApplicationRecord
has_many :items
end
The List controller
class ListsController < ApplicationController
before_action :authenticate_user!
layout 'backend'
def index
@lists = List.where(user_id: current_user.id)
end
def show
end
def new
@list = List.new
end
def edit
end
def create
@list = List.new(list_params)
@list.user = current_user
if @list.save
redirect_to list_path(@list.id), notice: 'List was successfully created.'
else
redirect_to list_path(@list.id), notice: 'List was not created.'
end
end
def update
respond_to do |format|
if @list.update(list_params)
format.html { redirect_to @list, notice: 'List was successfully updated.' }
format.json { render :show, status: :ok, location: @list }
else
format.html { render :edit }
format.json { render json: @list.errors, status: :unprocessable_entity }
end
end
end
def destroy
@list.destroy
respond_to do |format|
format.html { redirect_to lists_url, notice: 'List was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def list_params
params.require(:list).permit(:name, :items)
end
end
Not sure what to do about form - was trying something along the lines of http://apidock.com/rails/ActionView/Helpers/FormHelper/check_box