Home > Back-end >  undefined method `model_name' for #Array when using pagy gem
undefined method `model_name' for #Array when using pagy gem

Time:10-20

i got this problem:

undefined method `model_name' for #Array:0x00007f3e929cc430

{ count:     collection.count(:all),
     page:      params[vars[:page_param]||Pagy::VARS[:page_param]],
     item_path: "activerecord.models.#{collection.model_name.i18n_key}" }.merge!(vars)
   end

here is my data_controller.rb:

  def index
    @pagy, @datas = pagy(Data.active_only.where(data_location: @location).sort_by(&:id))
  end

here is my application_controller.rb

def pagy_get_vars(collection, vars)
    { count:     collection.count(:all),
     page:      params[vars[:page_param]||Pagy::VARS[:page_param]],
     item_path: "activerecord.models.#{collection.model_name.i18n_key}" }.merge!(vars)
   end

and lastly my view

<div>
<table id="tablestock" class="table_content table">
  <thead>
    <tr>
      <th>ID</th>
      <th>Date</th>
      <th class="sorting_disabled">Location</th>
      <th class="sorting_disabled">Name</th>
    </tr>
  </thead>

  <tbody>
    <% @datas.each do |data| %>
    <tr data-link="<%= data_path(data) %>"> 
      <td><%= data.id %></td>
      <td><%= data.created_at.strftime('%d %b %Y') rescue ("<b style='color:red; font-size:16px;'>ERROR</b>".html_safe)%></td>
      <td><%=data.data_location.location if data.location_id? %></td>
      <td><%= data.data_name.name if data.name_id? %></td>

    </tr>
    <% end %>
  </tbody>
</table>
  <div class="justify">
    <%= pagy_nav(@pagy).html_safe if @datas.present? %>
  </div>
</div>

CodePudding user response:

You are trying to call model_name on an Array model_name is a method of a ActiveRecord of ActiveRecord::Relation. You did not supply the code where you call the pagy_get_vars(collection, vars) method but you need to make sure that collection is some object type that has a model_name method like an ActiveRecord::Relation and not an Array.

Perhaps the problem is started here:

Data.active_only.where(data_location: @location).sort_by(&:id)

sort_by is creating an Array.

You could use:

Data.active_only.where(data_location: @location).order(:id)

This way the result is not an Array but an ActiveRecord::Relation.

  • Related