新手问题 多層類的 has_many 和 belongs_to

1272729223 · 2012年09月11日 · 最后由 fresh_fish 回复于 2012年09月12日 · 2189 次阅读

我現在有這幾個 model: Category,PostCategory,Post.

class Category < ActiveRecord::Base
  attr_accessible :name, :type
end

class PostCategory < Category
  has_many :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
  belongs_to :postcategory  #還是:post_category?
  attr_accessible :title, :content, :post_category_id #之前我命名是category_id
end

然後 controller 裡面無法獲取到@post_category

class PostsController < ApplicationController
  def index
     @post_category = PostCategory.find(params[:id])
     @posts = @post_category.posts
  end
end

現在訪問報錯: *ActiveRecord::RecordNotFound in PostsController#index ** Couldn't find PostCategory without an ID

需要 登录 后方可回复, 如果你还没有账号请 注册新账号