【问题标题】:Best way to display model data in a master layout in an MVC framework在 MVC 框架的主布局中显示模型数据的最佳方式
【发布时间】:2009-02-28 07:50:05
【问题描述】:

我有一个简单的 Rails 应用程序,它为所有页面使用主布局。我想在这个布局中有一个显示模型数据的页脚,这样无论你在哪个页面上都可以看到数据。

目前我只有一个控制器,有几个非常简单的视图被渲染到布局中,控制器中没有定义任何操作方法。布局类似于:

<div id="footer"><%= controller.get_data %></div>

get_data 当然只是从模型中提取数据。这似乎是一种糟糕的方法,因为我无法在不破坏布局的情况下添加更多控制器。

我的问题是:当请求可以由将任何视图呈现到该布局中的任何控制器处理时,从模型中检索数据以显示在主布局中的最佳方法是什么?应该在哪里定义 get_data,或者有什么更简洁的方法来处理这个问题?

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    你可以这样做:

    使用访问器方法定义通用控制器实例变量来存储当前模型类和实例:

    class ApplicationController
      attr_accessor :current_model_class, :current_model_instance
      helper_method :current_model_class, :current_model_instance
    end
    

    特别是控制器给它们赋值(你也可以把它放在一些过滤器之前或之后):

    class SomeController < ApplicationController
      def index
        self.current_model_instance = SomeModel.find(params[:id])
        self.current_model_class = SomeModel
      end
    end
    

    在将获取布局数据的所有模型中定义相同的类和实例方法:

    class SomeModel < ActiveRecord::Base
      def self.get_data
        # get class specific data
      end
    
      def get_data
        # get instance specific data
      end
    
    end
    

    并在你的布局文件中使用它:

    <div id="footer"><%= current_model_instance.get_data %></div>
    

    <div id="footer"><%= current_model_class.get_data %></div>
    

    【讨论】:

      【解决方案2】:

      您也可以在ApplicationController 中使用before_filter

      class ApplicationController < ActionController::Base
         before_filter :set_footer_data
      
         def set_footer_data
            @footer_data = MyModel.find(params[:id])
         end
      end
      

      然后在你的布局中:

      <div id="footer"><%= @footer_data %> </div>
      

      【讨论】:

        猜你喜欢
        • 2011-09-15
        • 2012-06-27
        • 1970-01-01
        • 1970-01-01
        • 2016-11-22
        • 1970-01-01
        • 2019-07-24
        • 2023-03-16
        • 2012-05-25
        相关资源
        最近更新 更多