enter image description hereI'm writing a to-do list app. Each user can have multiple list categories, and each list category can contain multiple list items:
class User < ApplicationRecord
has_many :list_categories, dependent: :destroy
has_many :list_items, through: :list_categories
class ListCategory < ApplicationRecord
belongs_to :user
has_many :list_items, dependent: :destroy
class ListItem < ApplicationRecord
belongs_to :list_category
In the index view of the list_category controller I have a list of the categories and a form for creating new categories, which works fine.
Each category in the index view has a link to the show action for that category. In the show view, I have a form for creating new list items for that category (so that the show page effectively acts as the 'new' page for list items) and code for showing the list items already created, but I haven't been able to get either to work.
In the list_categories controller I have:
def show
@list_category = current_user.list_categories.find(params[:id])
@list_item = @list_category.list_items.build
@list_items = @list_category.list_items
end
In the list_items controller:
def create
@list_category = current_user.list_categories.find(params[:id])
@list_item = @list_category.list_items.build(list_item_params)
redirect_to list_category_path(@list_category)
end
private
def list_item_params
params.require(:list_item).permit(:content)
end
The form I'm trying to use is:
<%= form_for(@list_item) do |f| %>
<%= f.text_field :content %>
<%= f.submit "Add", class: "btn btn-primary" %>
<% end %>
And the code for showing each list item in the list category:
<% @list_items.each do |item| %>
<%= item.content %>
<% end %>
When I try to submit a list item in the form in the show action, I get this error in the list_items controller's create action:
Couldn't find ListCategory without an ID
because of the line
@list_category = current_user.list_categories.find(params[:id])
Am I right in thinking including @list_item as the form_for argument automatically maps the form to the list_item create action? Even when I manually put an id number into the error line and try to create a list item, when I call the list_items method on the rrelevant category, it says it doesn't contain any list_items, so the for still doesn't work.
This is the server log:
Started POST "/list_items" for 127.0.0.1 at 2017-08-12 13:33:24 +0100
Processing by ListItemsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"F9kqlwQryyCFsddetAWF4WcI8g2x3c2hMCfaHGWad8QT1OHeHmdvzIFtEoqB8iYyE7vi0CWN+BChFZrpc1VcYw==", "list_item"=>{"content"=>"task"}, "commit"=>"Add"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.1ms)
ActiveRecord::RecordNotFound (Couldn't find ListCategory without an ID):