【发布时间】:2019-11-19 20:04:32
【问题描述】:
我确定这确实很愚蠢,但我似乎找不到问题所在。
我正在尝试拨打Reservation.last.card,但收到错误消息
Reservation Load (0.3ms) SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."id" DESC LIMIT $1 [["LIMIT", 1]]
NoMethodError: undefined method `card' for #<Reservation:0x090d440e130>
Did you mean? card_id
迁移 + 架构
class AddCardToReservations < ActiveRecord::Migration[5.2]
def change
add_reference :reservations, :card, foreign_key: true
end
end
create_table "reservations", force: :cascade do |t|
t.bigint "park_id"
t.bigint "card_id"
t.index ["card_id"], name: "index_reservations_on_card_id"
t.index ["park_id"], name: "index_reservations_on_park_id"
end
型号
class Reservation < ApplicationRecord
has_one :card
belongs_to :park
end
class Card < ApplicationRecord
belongs_to :park
has_many :reservations
end
【问题讨论】:
-
对于初学者:将
has_one :card更改为belongs_to :card。您可能还需要重新启动控制台。 -
谢谢 Marek,我知道这很愚蠢。
标签: ruby-on-rails activerecord