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

Time:04-05

In previous versions of rails I could call a secondary model's columns like: book.author.name

Now I get this error.

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

CodePudding user response:

You need to change

class ThingStatus < ApplicationRecord
  belongs_to :thing
end

and a thing_id in the thing_statuses-table

CodePudding user response:

Change has_one relationship to belongs_to, and make sure you have thing_status_id column for Thing

belongs_to is where the foreign key is.

has_one or has_many is on the opposite side of 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
  • Related