【问题标题】:How to show has_many component in Ruby on Rails如何在 Ruby on Rails 中显示 has_many 组件
【发布时间】:2019-12-17 13:52:50
【问题描述】:

我的 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

Receipt Model 有这样的记录。

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>

【问题讨论】:

    标签: ruby-on-rails ruby routing


    【解决方案1】:

    问题是您试图通过在集合上调用 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。如果您要访问收据模型上的任何关系,您可以急切加载您需要减少对数据库的命中的任何关系。

    它会像这样改变控制器/视图:

    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 %>
    

    【讨论】:

    • 您可能想对急切加载发表评论以避免 N+1 问题。
    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多