我确定这确实很愚蠢,但是我似乎找不到问题。
我正在尝试致电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
答案 0 :(得分:2)
Reservation
类中的行...
has_one :card
表示card
对象不是reservation_id
,而card_id
对象中的外键是reservation
,所以您想要的就是。 ..
belongs_to :card