How is the best way to load Category model, for ProductController in new, edit update and create actions
Product has categories collection
class Product < ActiveRecord::Base
has_many :categories
end
Always for new, edit, create and update actions, I need to load the categories collection to populate a check_box_tag list
The "baby steps" for this situation is:
class Admin::ProductsController < Admin::AdminApplicationController
def new
@product = Product.new
@categories = Category.all
end
def edit
@product = Product.find(params[:id])
@categories = Category.all
end
def create
@product = Product.new(params[:product])
if @product.save
flash[:notice] = 'Product was successfully created'
redirect_to edit_admin_product_path(@product)
else
@categories = Category.all
render :new
end
end
def update
@product = Product.find(params[:id])
@product.update_attributes(params[:product])
if @product.save
flash[:notice] = 'Product was successfully updated'
redirect_to edit_admin_product_path(@product)
else
@categories = Category.all
render :edit
end
end
end
I don't want to load always Category.all in different situations for same purpose
Options:
First - load categories over the view:
<% Category.all.each do |cat| %>
<li>
<%= check_box_tag .... %>
</li>
<% end %>
:/
Second - load categories over the ProductsHelper :
module ProductsHelper
def categories
Category.all
end
end
:/
"Third" - Exist a filter like 'before_render'?
class Admin::ProductsController < Admin::AdminApplicationController
before_render :load_categories :edit, :new
def load_categories
@categories = Category.all
end
end
:D :D :D
What's the rails way for this situations?
Best Regards, Pablo Cantero