简体   繁体   English

使用Ruby on Rails进行敏捷Web开发:视图如何访问此实例变量

[英]Agile web development with Ruby on Rails: how does the view have access to this instance variable

In chapter 9 of Agile Web development with Rails 4 在使用Rails进行敏捷Web开发的第9章中,第4章

You have a model cart.rb which has many line items 您有一个模型cart.rb,其中包含许多订单项

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. 添加订单项时,您将调用line_items_controller的create方法。 Before create method is called, it calls the set_cart method of the current cart module by such 在调用create方法之前,它会这样调用当前购物车模块的set_cart方法

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? 我的问题是该视图如何访问在current_cart模块中定义的@cart实例变量?

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. 您的代码做的最后一件事是重定向到@ line_item.cart,这是CartsController中的show动作。

So you have a show action, that has an instance variable @cart so it can be used in the views. 因此,您具有一个show动作,该动作具有一个实例变量@cart,因此可以在视图中使用它。

Or if you do not have a show action, then rails is smart enough to make a show action from the redirect url. 或者,如果您没有显示动作,那么Rails足够聪明,可以从重定向URL进行显示动作。 and know to make an instance variable @cart using the url id. 并知道使用网址ID来创建实例变量@cart。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM