Rails7:如何调用外键模型列?

Rails 7: How to I call foreign key model columns?

在以前的 rails 版本中,我可以像这样调用辅助模型的列: book.author.name

现在我得到这个错误。

SQLite3::SQLException: no such column: thing_statuses.thing_id

_thing.html.erb

<div id="<%= dom_id thing %>">
  <p>
    <strong>Status:</strong>
    <%= thing.thing_status.status %>
  </p>
  <p>
    <strong>Name:</strong>
    <%= thing.name %>
  </p>
</div>

app/models/thing.rb

class Thing < ApplicationRecord
  has_one :manufacturer
  has_one :thing_status
  has_rich_text :note
  has_many_attached :images
end

app/models/thing_status.rb

class ThingStatus < ApplicationRecord
  has_many :things
end

你需要改变

class ThingStatus < ApplicationRecord
  belongs_to :thing
end

thing_idthing_statuses-table

has_one 关系更改为 belongs_to,并确保 Thing

thing_status_id

belongs_to是外键所在的地方。

has_onehas_many在belongs_to

的对面
# Table name: things
#
#  id               :integer(11)    not null, primary key
#  thing_status_id  :integer(11)    not null
#  ...
class Thing < ApplicationRecord
  belongs_to :thing_status
end
# Table name: thing_statuses
#
#  id               :integer(11)    not null, primary key
#  ...
class ThingStatus < ApplicationRecord
  has_many :things
end