【问题标题】:Scope of the variable in the partial file in railsrails中部分文件中变量的范围
【发布时间】:2015-07-11 12:55:03
【问题描述】:

我想在控制器中定义的部分文件中使用“列”实例变量并且它正在工作,但我想知道有没有更好的方法来做到这一点?

控制器:

def index
     ### code here ####
    @columns= []
    Model.column_names.each do |col|
      cnd = "#{col}"
      if cnd == 'id' || cnd == 'abc_id' || cnd == "created_at" || cnd =="updated_at"
         next
      end
        @columns << cnd
    end
  end

index.html.haml

%fieldset.form-columned
  .row-fluid
   #### code here ######
   = render :partial => 'admin/partial', locals: {columns:@columns}

在部分文件中:_partial

    - columns.each do |cols|
      %tbody
        %td #{cols}
        %td

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    可以在 Controller 中进行一次重构:

    def index
      reject_columns = ["id", "abc_id", "created_at", "updated_at"]
      @columns = Model.column_names.reject{ |c| reject.include?(c)  }
    end
    

    对于_partial 重构,可以直接在_partial 中使用@columns,不需要传递locals,因为它是一个实例变量。如果你愿意部分名称,你可以使用集合的渲染。请参阅http://guides.rubyonrails.org/layouts_and_rendering.html 中的渲染集合部分

    【讨论】:

      【解决方案2】:

      您可以在局部变量中访问实例变量 - 即直接在 index.html.haml 中访问 @columns 而无需将其作为本地变量传入。但是,the consensus 似乎是您不应该这样做的。因此,就您的实例变量的使用而言,我相信您当前的行为是正确的(尽管您的控制器代码可以重构以保持整洁)。

      【讨论】:

        猜你喜欢
        • 2018-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-10
        相关资源
        最近更新 更多