I have three tables: recipes, scrapbooks and scrapbook_entries.
My scrapbook_entries is a join table containing (:recipe_id and :scrapbook_id)
The recipe and scrapbook already exist and I am trying to make a form which allows the user to select a scrapbook (from current_user.scrapbooks) and then click 'save' which will take the current recipe (form will be in recipe view) and add the scrapbook_id and recipe_id to the scrabook_entries table.
I already have a scrapbook_entries model and controller. My controller looks like this:
class ScrapbookEntriesController < ApplicationController
def create
@recipe = current_user.recipes.find(params[:recipe_id])
@scrapbook = current_user.scrapbooks.find(params[:scrapbook_id])
@entry = current_user.scrapbook_entries.build(scrapbook: @scrapbook)
if @entry.save
flash[:success] = "Added '#{@recipe.name}' to scrapbook '#{@scrapbook.name}'"
else
flash[:error] = "Could not add to scrapbook"
end
redirect_to @recipe
end
end
My form within the recipe view looks like this:
<%= form_for(@scrapbook_entry, :url => scrapbook_entries_path(params[:id])) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.number_field :scrapbook_id, placeholder: "Scrapbook ID" %>
<%= f.hidden_field :recipe_id, :value => @recipe.id %>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
As you can see at the moment the user just has to enter the scrapbook_id he/she wants to save it to. I would eventually like to add a list of scrapbooks in a select field but I have had trouble with that so any suggestions would be welcomed!
My form currently renders a "Couldn't find Recipe without an ID" error in the controller once I click submit. Any ideas what I am doing wrong here?
EDIT:
scrapbook.rb
belongs_to :user
has_many :recipes, through: :scrapbook_entries
has_many :scrapbook_entries
recipe.rb
belongs_to :user
has_many :scrapbooks, through: :scrapbook_entries
scrapbook_entry.rb
has_one :recipe
has_one :scrapbook