Responsive Ad Area

Share This Post

test

Using controller concerns to hide logic

I’m building an e-commerce application that implements the active_record-acts_as gem to create a traditional inheritance hierarchy between Product (the parent class) and all of Product’s subclasses (ie Book, Furniture, etc..).

Context

I’ve successfully setup the generic/polymorphic (like) ProductsController to handle the creation/update of any subclass of Product, which looks something like this…(although I have hardcoded isbn in product_params in this example to simplify and concentrate the question on where to place the code..and also to make my tests pass..which gives me a warm and fuzzy).

class ProductsController < ApplicationController
  before_action :set_category, :set_product_type, only: [:new, :create]
  before_action :set_product, only: [:show, :edit]

  def show
  end

  def new
  end

  def create
    @product = @product_type.new product_params
    @product.category = @category

    if @product.save 
      redirect_to product_path @product.slug
    else
      render :new
    end
  end

  ...

  private

  def set_category
    @category = Category.friendly.find(params[:category_id])
  end

  def set_product
    @product = Product.friendly.find(params[:id]).specific
  end

  def set_product_type
    @product_type = @category.name.singularize.capitalize.constantize
  end

  def product_params
    params.require(:product).permit(:name, actable_attributes: [# generate @product_type specific permitted params])
  end
end

Question

I’m not looking for a code example but more of an answer that can explain where the best place is to put the code that generates the dynamic permitted params in the private product_params nested actable_attributes attrs.
My first inclination is to just create a controller concern and include it in ProductsController. But, maybe creating a method in the ProductsController will make whats going on more clear?


Using controller concerns to hide logic
Using controller concerns to hide logic
test
{$excerpt:n}

Share This Post

Leave a Reply

Your email address will not be Publishedd. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>