加载其他模型集合以进行新的,编辑更新和创建操作的最合理方式是什么? [英] What's the rails way to load other models collections for new, edit update and create actions?
问题描述
对于在新的ProductController中加载类别模型的最佳方式是什么,如何编辑更新并创建操作
How is the best way to load Category model, for ProductController in new, edit update and create actions
产品具有类别集合
class Product < ActiveRecord::Base
has_many :categories
end
始终用于新建,编辑,创建和更新操作,我需要加载类别集合以填充check_box_tag列表
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
我不想总是加载Category.all在diff中出于相同目的的错误情况
I don't want to load always Category.all in different situations for same purpose
选项:
首先-在视图上加载类别:
First - load categories over the view:
<% Category.all.each do |cat| %>
<li>
<%= check_box_tag .... %>
</li>
<% end %>
:/
第二-负载类别在ProductsHelper上:
Second - load categories over the ProductsHelper :
module ProductsHelper
def categories
Category.all
end
end
:/
第三-是否存在类似 before_render的过滤器?
"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?
最好的问候,
Pablo Cantero
Best Regards, Pablo Cantero
推荐答案
在您的控制器,或者如果需要,在application_controller.rb中:
In your controller, or if needed elsewhere, in application_controller.rb:
def all_categories
@all_categories ||= Category.all
end
helper_method :all_categories
第一次调用它将点击数据库,稍后它将返回控制器实例变量。
The first time it's called, it will hit the db, and later it will return the controller instance variable.
这篇关于加载其他模型集合以进行新的,编辑更新和创建操作的最合理方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!