Rails包含 - 歌曲中没有找到名为“专辑”的协会;也许你拼错了吗?

时间:2016-04-05 06:00:43

标签: ruby-on-rails ruby-on-rails-4

我有以下架构

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

我收到以下错误

  

宋没有找到名为'专辑'的协会;也许你   拼错了吗?

1 个答案:

答案 0 :(得分:1)

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

includes应该使用关联名称。

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