ruby-on-railsrubyruby-on-rails-4rails-cells

New and Create actions using Cells


I am trying to implement the Cells gem in a Rails 4 project.

I am a little bit confused about rendering a form Cell for a model. I looked around on Google but can't seem to find a tutorial covering this. Most tutorials only cover a :show Cell.

  1. Is it possible / good practice to implement a Cell Form?
  2. How do you go about creating and rendering this Cell? (I assume this will be similar to the :show Cell)
  3. Where does the cell fir into the form submission process flow? Are params still posted to the controller or to the Cell? Where do I do my Form submission validation?

Can anybody please help me clarify or point me to a tutorial covering this issue?


Solution

    1. 'Best practice' is hardly a thing. But I think cells provide a nice pattern. The great thing is the testability. You can write really nice tests that check whether expected HTML elements are present and what content they should have. This makes it very easy to test an entire page through small cell test rather than one big page test (which you'd never do'). So why not test forms as well?

    2. Yes it is pretty similar, please see my example at the end. (The code is a demo and it is based on my short experiments with cells, I am sure a cell-expert could improve on it).

    3. The cell's form can simply post to the controller as any other form would from within a partial. A cell is just a view layer. The form within the cell points to a url and urls are routed to controllers.

      # controllers/products_controller.rb
        ...
        def new
          @product = Product.new
        end
      
        def create
          @product = Product.new(product_params)
        end
        ...
      
      # views/products/new.html.erb
      
      <div class='new_product_form'>
        <%= render_cell :products, :new, product: @product %>
      </div>
      
      # cells/products_cell.rb
      
      class SubscriptionCell < Cell::Rails
        def new(params)
          @product = params[:product]
          render
        end
      end
      
      # cells/products/new.html.erb
      
      <%= simple_form_for @product do |f| %>
        <%= f.input :name %>
        <%# etc... %>
      <% end %>