has_many belongs_to不工作

时间:2014-05-17 20:51:43

标签: ruby-on-rails associations

我花了最后5个小时试图弄清楚为什么这个简单的协会不会起作用。它以前工作过。我提供了尽可能多的代码。

错误:

SQLite3::SQLException: no such column: Category: SELECT "videos".* FROM "videos"  WHERE "videos"."category_id" = ?  ORDER BY Category ASC

模型

class Video < ActiveRecord::Base

belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :videos, -> { order "Category ASC" }
end

路线

Myflix::Application.routes.draw do

  root to: "static_pages#front"

require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'


    resources :videos do
        collection do
            get :search, to: "videos#search"
        end
        resources :reviews
    end

    namespace :admin do
        resources :videos, only: [:new, :create]
        resources :payments
        resources :categories, only: [:new, :create, :index, :destroy,  :edit, :update, :show]
    end

    resources :categories


end

控制器

class CategoriesController < ApplicationController
before_filter :require_user

def index
    @categories = Category.all
    @videos = Video.all
end

def show
    @category = Category.find(params[:id])
end

def destroy
    Category.find(params[:id]).destroy
    flash[:success] = "Category Deleted."
    redirect_to admin_categories_path
end

private

def category_params
    params.require(:category).permit(:category)
end
end

查看:

%section.genre
  %header.clearfix
    %h1=@category.category
  %article.row
    -if @category.videos.any?
      -@category.videos.each do |video|
        .video.col-sm-2
          = link_to image_tag(video.small_cover_url), video
    - else
      .video.col-sm-2
         No videos in this category

db schema

ActiveRecord::Schema.define(version: 20140517182911) do

 create_table "categories", force: true do |t|
    t.string   "category"
    t.datetime "created_at"
    t.datetime "updated_at"
 end

  create_table "videos", force: true do |t|
    t.string   "title"
    t.string   "video_description"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "category_id"
    t.string   "large_cover"
    t.string   "small_cover"
    t.string   "video_url"
  end

 end

错误是在@ categories.videos.each行提出的,我完全不知道。一切似乎都设置正确。

1 个答案:

答案 0 :(得分:4)

使用此:

 class Category < ActiveRecord::Base
    has_many :videos, -> { order "category_id ASC" }
 end

category_id表格中有videos列而不是Category,这就是您收到错误的原因SQLite3::SQLException: no such column: Category