techquestion
techquestion

Reputation: 489

Reservation.last.card => NoMethodError: undefined method `card' for #<Reservation:0x0090d440e130> Did you mean? card_id

I'm sure it something really stupid, but I cannot seem to find the issue.

I'm trying to call Reservation.last.card, but get the error

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

migration + schema

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

models

class Reservation < ApplicationRecord
  has_one :card
  belongs_to :park
end

class Card < ApplicationRecord
  belongs_to :park
  has_many :reservations
end

Upvotes: 0

Views: 26

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36880

the line in the Reservation class...

has_one :card

Implies that the card object has a reservation_id which isn't the case, the foreign key is card_id in the reservation object, so what you want is...

belongs_to :card

Upvotes: 2

Related Questions