1

I want to use "columns" instance variable in partial file defined in the controller and it is working, but I would like to know is there better ways to do it ?

Controller:

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}

in partial file : _partial

    - columns.each do |cols|
      %tbody
        %td #{cols}
        %td
Sandeep Kumar M
  • 3,841
  • 3
  • 38
  • 59

2 Answers2

0

One refactor can be done in Controller:

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

For _partial refactor, you can directly user @columns in the _partial, you don't need to pass the locals, as it is an instance variable. If you are willing to the partial name, you can use rendering of collection. See Rendering Collection section in http://guides.rubyonrails.org/layouts_and_rendering.html

roxxypoxxy
  • 2,973
  • 1
  • 21
  • 28
0

You can access instance variables in partials - i.e. access @columns directly in index.html.haml without passing it in as a local. However, the consensus seems to be that you shouldn't. So in terms of the use of your instance variable, I believe your current behaviour is correct (although your controller code could be refactored for neatness).

Community
  • 1
  • 1
PGleeson
  • 381
  • 1
  • 3
  • 9