Rails 包括 - 在 Song 上找不到名为 'albums' 的关联;也许你拼错了?



我有以下架构

create_table "songs", force: :cascade do |t|
    t.string   "title",       null: false
    t.text     "lyrics",      null: false
    t.string   "youtube_url"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "user_id"
    t.integer  "album_id"
    t.integer  "artist_id"
  end

当我尝试进行以下时

  def index
    @songs ||= find_songs
  end
private
def find_songs
    songs = Song.includes(:albums).order(updated_at: :desc).paginate(:page => params[:page], :per_page => 2)
    songs = songs.order(:title) if params['sort_by'] == "title"
    songs
  end

我得到以下错误

在Song上找不到名为"albums"的关联;也许你拼错了吗?

如果您有Album has_many songsSong belongs_to album的关联,请尝试此操作。

includes应采用关联名称。

songs = Song.includes(:album).order(updated_at: :desc).paginate(:page => params[:page], :per_page => 2)

最新更新