[英]Paper trail display has many objects
I'm using the paper trail gem to track version changes on order web application. 我正在使用纸张跟踪宝石来跟踪订单Web应用程序上的版本更改。 I'm having trouble displaying the has_many versions
我在显示has_many版本时遇到问题
Order model: 订单型号:
class Order < ActiveRecord::Base
has_paper_trail
has_many :line_items, dependent: :destroy, inverse_of: :order, order: "position", autosave: true
end
line item model: 订单项模型:
class LineItem < ActiveRecord::Base
belongs_to :order, inverse_of: :line_items
has_paper_trail
end
Order Controller: 订单控制器:
@order = Order.find(params[:id])
@versions = PaperTrail::Version.where(item_id: params[:id]).order('created_at ASC')
@line_items = LineItem.find_all_by_order_id(params[:id])
@line_item_versions = @line_items.versions
history html: 历史HTML:
<% @line_item_versions.each_with_index do |version, index| %>
<b>Version: </b><%= index + 1 %><br/>
Event ID: <%= version.id %><br/>
<b>Target:</b> <%= version.item_type %>
<small>(id: <%= version.item_id %>)</small>; <b>action</b> <%= version.event %>;<br/>
<% end %>
The problem is the .versions
works when a single object (from .find
) is found. 问题是,当找到单个对象(来自
.find
)时, .versions
可以工作。 However, when an array of objects (from the .find_all_by
) is passed to the .versions
it returns this error 但是,当对象数组(来自
.find_all_by
)传递给.versions
它将返回此错误
undefined method `versions' for #<Array:0x007f859d37eb30>
You are defining: 您正在定义:
@line_items = LineItem.find_all_by_order_id(params[:id])
Which means @line_items
is an Array of several LineItem records. 这意味着
@line_items
是包含多个LineItem记录的数组。 Then, you call: 然后,您致电:
@line_item_versions = @line_items.versions
But the .versions
method is an instance method of LineItem (one line_item has_many versions
). 但是
.versions
方法是LineItem的实例方法(一个line_item has_many versions
)。 This causes the error undefined method 'versions' for Array
( @line_items
is an array here). 这会导致
undefined method 'versions' for Array
出现错误的undefined method 'versions' for Array
( @line_items
是此处的数组)。
To solve this problem, I think you should do the following (but there is many options, depending on what you want to do): 为了解决此问题,我认为您应该执行以下操作(但是有很多选择,具体取决于您要执行的操作):
<% @line_items.each do |line_item| %>
<%= line_item.name %>
<% line_item.versions.each_with_index do |version, index| %>
<b>Version: </b><%= index + 1 %><br/>
Event ID: <%= version.id %><br/>
<b>Target:</b> <%= version.item_type %>
<small>(id: <%= version.item_id %>)</small>; <b>action</b> <%= version.event %>;<br/>
<% end %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.