Getting undefined method for a polymorphic relation even though I've set relations

Getting a NoMethod error when setting a polymorphic relationship in rails 5.

I've followed the instructions here: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

I'm running rails 5.2

Here are my models:

class Image < ApplicationRecord
    belongs_to :imageable, polymorphic: true
    validates :url,  :presence => true
end

class Trip < ApplicationRecord
  validates :name,  :presence => true
  # validates :start_date,  :presence => true
  # validates :end_date,  :presence => true
  belongs_to :user
  has_many :todo, :dependent => :destroy
  has_many :destination, :dependent => :destroy
  has_many :events, through: :destination
  has_many :image, as: :imageable

  def formatted_arrival_time
    self.arrival_time.strftime("%H:%M")
  end

  def formatted_departure_time
    self.departure_time.strftime("%H:%M")
  end
end

class Destination < ApplicationRecord
  validates :title,  :presence => true
  belongs_to :trip
  has_many :event, :dependent => :destroy
  has_many :image, as: :imageable
end

Then in my controller:

# GET /images
        def index_trip
            if params[:page] && params[:per_page]
              trip = Trip.find(params[:trip_id])
              @images = Trip.image.all

              paginate json: @images, meta: {
                total: @images.count,
                per_page: params[:per_page].to_i, 
                page: params[:page].to_i,
                pages: (@images.count / params[:per_page].to_f).ceil
              }
            else
                trip = Trip.find(params[:trip_id])
                @images = Trip.image.all

              render json: @images
            end
        end

Any ideas on what I'm doing wrong here would be greatly appreciated.

1 answer

  • answered 2019-08-24 00:41 Scott Davies

    Turns out a little type on Trip should be 'trip'