Rails has_one 关联的未定义方法错误 (Rails 5)

Undefined method error with Rails has_one association (Rails 5)

我正在尝试访问视图中关联模型的方法,但出现未定义方法错误

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

。感谢您的帮助!

索引视图:

<% @actuals.each do |actual| %>
  <% if actual.procedures.present? %>
    <% actual.procedures.each do |procedure| %>
     <tr>
       <td><%= procedure.cpt_code.id %></td>
       <td><%= procedure.description %></td>
     </tr>
    <% end %>
  <% end %>
<% end %>

控制器:

  def index
    @actuals = Actual.all
  end

型号:

class Actual < ApplicationRecord
  has_many :actual_procedures, :dependent => :destroy
  has_many :procedures, through: :actual_procedures

class ActualProcedure < ApplicationRecord
  belongs_to :procedure
  belongs_to :actual
end

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
end

class CptCode < ApplicationRecord
  has_one :procedure

架构中的过程:

  create_table "procedures", force: :cascade do |t|
    t.bigint "cpt_code_id"
    t.string "code"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cpt_code_id"], name: "index_procedures_on_cpt_code_id"
  end

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

您在 procedures table 中没有 cpt_code。也许你的意思是 cpt_code_id.

更新:

实际原因是您没有在 Procedure 模型

中为 cpt_code 定义关联
class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
  belongs_to :cpt_code # you should have this
end