[英]undefined method `model_name' for #Array when using pagy gem
i got this problem:我遇到了这个问题:
undefined method `model_name' for #Array:0x00007f3e929cc430
#Array:0x00007f3e929cc430 的未定义方法`model_name'
{ 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:这是我的 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这是我的 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>
You are trying to call model_name on an Array model_name is a method of a ActiveRecord of ActiveRecord::Relation.您试图在数组上调用 model_name model_name 是 ActiveRecord::Relation 的 ActiveRecord 的一种方法。 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.
您没有提供调用 pagy_get_vars(collection, vars) 方法的代码,但您需要确保集合是某种具有模型名称方法(如 ActiveRecord::Relation)而不是数组的对象类型。
Perhaps the problem is started here:也许问题是从这里开始的:
Data.active_only.where(data_location: @location).sort_by(&:id)
sort_by is creating an Array. sort_by 正在创建一个数组。
You could use:你可以使用:
Data.active_only.where(data_location: @location).order(:id)
This way the result is not an Array but an ActiveRecord::Relation.这样,结果不是数组而是 ActiveRecord::Relation。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.