I'm probably trying too hard for my first website but i wanted to make a dropdown on a (bootstrap) navbar to be flexible, and show the names of the saved work categories.
This is what i've tried to do in the application.html.erb file :
<ul class="dropdown-menu">
<% @workcategory.each do |workcategory| %>
<li><%= workcategory.name%></li>
<% end %>
Failed with error undefined method
each' for nil:NilClasson the
<% @workcategory.each do |workcategory| %>` line.
This is the workcategories controller :
class WorkcategoriesController < ApplicationController
before_action :find_workcategory, only: [:edit, :update, :destroy]
def index
@workcategories = Workcategory.all.order("created_at DESC")
end
def new
@workcategory = Workcategory.new
end
def create
@workcategory = Workcategory.new(post_params)
if @workcategory.save
flash[:notice] = "Workcategory created"
redirect_to(:action=>'index', :workcategory_id => @workcategory.id)
else
@workcategories = Workcategories.order()
render('new')
end
end
def edit
end
def update
end
def destroy
@workcategory.destroy
redirect_to workcategory_path
end
private
def find_workcategory
@workcategory=Workcategory.find(params[:id])
end
def post_params
params.require(:workcategory).permit(:name)
end
end
Any tips and help are welcome, even non-related to the initial question :) Thank you
If you want it in all ur actions, it is wise to put it in your application_controller.rb
.
before_filter :set_work_categories
def set_work_categoriers
@w_categories = Workcategory.all.order("created_at DESC")
end
This should work fine.
Also, a tip.
You can use default_scope {order(created_at: :desc)}
in your model WorkCategory.rb
Then you can use this like,
def set_work_categoriers
@w_categories = Workcategory.all
end
I would recommend changing the variable name to @w_categories or else it will conflict with your @work_categories name in index
action.
In your application.html.erb
file, change
<% unless @w_categories.nil? %>
<ul class="dropdown-menu">
<% @w_categories.each do |workcategory| %>
<li><%= workcategory.name%></li>
<% end %>
</ul>
<%end>
I guess this should do the trick
If we talk about index
action, then you just forgot to use appropriate variable:
<ul class="dropdown-menu">
<% @workcategories.each do |workcategory| %>
<li><%= workcategory.name%></li>
<% end %>
Update
If you want to have this in all actions, then initialize @workcategories
in before_action
:
# your_controller.rb
before_action :initialize_work_categories
def initialize_work_categories
@workcategories = Workcategory.all.order("created_at DESC")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With