Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the rails way to load other models collections for new, edit update and create actions?
    primarykey
    data
    text
    <p>How is the best way to load Category model, for ProductController in new, edit update and create actions </p> <p>Product has categories collection</p> <pre><code>class Product &lt; ActiveRecord::Base has_many :categories end </code></pre> <p>Always for new, edit, create and update actions, I need to load the categories collection to populate a check_box_tag list</p> <p>The "baby steps" for this situation is:</p> <pre><code>class Admin::ProductsController &lt; 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 </code></pre> <p>I don't want to load always Category.all in different situations for same purpose </p> <p>Options:</p> <p>First - load categories over the view: </p> <pre><code>&lt;% Category.all.each do |cat| %&gt; &lt;li&gt; &lt;%= check_box_tag .... %&gt; &lt;/li&gt; &lt;% end %&gt; </code></pre> <p>:/</p> <p>Second - load categories over the ProductsHelper :</p> <pre><code>module ProductsHelper def categories Category.all end end </code></pre> <p>:/</p> <p>"Third" - Exist a filter like 'before_render'?</p> <pre><code>class Admin::ProductsController &lt; Admin::AdminApplicationController before_render :load_categories :edit, :new def load_categories @categories = Category.all end end </code></pre> <p>:D :D :D</p> <p>What's the rails way for this situations? </p> <p>Best Regards, Pablo Cantero</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload