如何在 Rails 上显示 Ruby 中的 has_many 组件

How to show has_many component in Ruby on Rails

我的 show.html.erb 文件如下。

<h1>details of policyid: <%= @policies.id %></h1>

<p><%= @policies.receipts.receipt_day %></p>

我的控制器如下所示。

def show
    @policies=Policy.find(params[:id])
end

型号如下

class Policy < ApplicationRecord
    has_many :receipts
end
class Receipt < ApplicationRecord
  belongs_to :policy
  has_many :outpatients
  has_many :hospitalizations
  has_many :surgeries
  has_many :others
end

收据模型有这样的记录。

2.6.3 :005 > Receipt.all
  Receipt Load (0.3ms)  SELECT `receipts`.* FROM `receipts`
 => #<ActiveRecord::Relation [#<Receipt id: 1, receipt_day: "2019-11-01", policy_id: 1, created_at: "2019-11-20 08:21:21", updated_at: "2019-11-20 08:21:21">]> 

我想在策略显示文件中显示 receipt_day。这可能吗?
我遇到了如下错误。 如果有人遇到同样的问题,请告诉我。

NoMethodError in Policies#show
Showing /home/ec2-user/environment/calendar_test/app/views/policies/show.html.erb where line #3 raised:
undefined method `receipt_day' for #<Receipt::ActiveRecord_Associations_CollectionProxy:0x00007f67fc0664e8>

问题是您试图通过在集合上调用 Reciept 属性来访问它。你的控制器应该看起来像

def show
    @policy = Policy.find(params[:id])
end

然后在您希望在每张收据上看到 receipt_days 的视图中,您可以遍历集合

<h1>details of policyid: <%= @policy.id %></h1>
<% @policy.receipts.each do |receipt| %>
  <p><%= receipt.receipt_day %></p>
<% end %>

正如@jvillian 所说的 N+1。如果您要访问收据模型上的任何关系,您可以急切加载您需要的任何关系,以减少对数据库的点击。

它将 controller/view 更改为:

def show
    @policy = Policy.find(params[:id])
    @receipts = @policy.receipts.includes(:outpatients,...) #include any relationship that you're going to access in the view
end

<h1>details of policyid: <%= @policy.id %></h1>
<% @receipts.each do |receipt| %>
  <p><%= receipt.receipt_day %></p>
<% end %>