Question

In chapter 9 of Agile Web development with Rails 4

You have a model cart.rb which has many line items

class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy
end

You also have a line items model

class LineItem < ActiveRecord::Base
  belongs_to :product
  belongs_to :cart
end

in controllers/concerns you define a module current cart

module CurrentCart
    extend ActiveSupport::Concern    
    private    
      def set_cart
        @cart = Cart.find(session[:cart_id])
        rescue ActiveRecord::RecordNotFound
            @cart = Cart.create
            session[:cart_id] = @cart.id
        end
      end

When you add a line item, you call the create method of line_items_controller. Before create method is called, it calls the set_cart method of the current cart module by such

before_action :set_cart, only: [:create]

After line item is posted, it redirects the page to the cart index page as such

format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }

When the view is displayed, it uses

  <% @cart.line_items.each do |item| %>
    <li><%= item.product.title %></li>
  <% end %>

My question is how does this view have access to @cart instance variable which is defined in the current_cart module?

Was it helpful?

Solution

It is not really using the module to know the instance variable. The last thing your code did was to redirect to @line_item.cart which is the show action in the CartsController.

So you have a show action, that has an instance variable @cart so it can be used in the views.

Or if you do not have a show action, then rails is smart enough to make a show action from the redirect url. and know to make an instance variable @cart using the url id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top