I am having an issue with my update method in my recipes controller where I cannot create a new category. Category is a nested resource within recipes. This is my update method
def update
if current_user.id != @recipe.category.user_id
flash.now[:notice] = "You cannot update a recipe that you did not author."
redirect_to recipes_path
else
@recipe.update(recipe_params)
flash.now[:notice] = "#{@recipe.title} has been updated."
redirect_to recipe_path
end
if @category
recipe.build_category
end
end
I just recently added the if @category recipe.build_category
but that didn’t do anything.
This is my recipe strong params:
def recipe_params
params.require(:recipe).permit(
:title,
:description,
:category_id,
category_attributes: [:name],
instructions_attributes: [:id,
:step, :_destroy
]
)
end
And my recipes controller before actions:
before_action :redirect_if_not_logged_in
before_action :find_recipe, only: [:show, :edit, :update, :destroy]
before_action :find_category, only: [:index, :new, :create]
I also have this language in my recipes _form:
<%= f.fields_for :category, recipe.build_category do |cb| %>
<div style="margin-left:30px">
<%= cb.label :name %>
<%= cb.text_field :name %>
</div>
<% end %>
and then this in my recipes edit.html.erb
<%= render partial: "form", locals: {recipe: @recipe, category: @category, button_name: "Update Recipe"}%>
These are my recipes & categories routes:
resources :recipes, only: [:index, :show, :new]
end
resources :recipes do
resources :categories, only: [:index, :new, :create]
end
resources :users, only: [:show, :new] do
resources :recipes, only: [:index]
end
This is my recipes model:
belongs_to :category
accepts_nested_attributes_for :category, reject_if: :all_blank
has_many :instructions, dependent: :destroy
accepts_nested_attributes_for :instructions, reject_if: :all_blank, allow_destroy: true
validates :title, presence: true
validates :instructions, presence: true
validates :description, presence: true
end
Does anyone know why I wouldn’t be able to create
the category within an existing recipe?
**Side note - my flash errors are also not working. Thanks in advance for any help.