0

我有以下代码

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :posts, :through => :categorizations
end

class Post < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
end

class NewsArticle < Post
end

好的,看起来不错。我正在尝试从类别中获取所有 NewsArticle

@news_articles = NewsArticle.paginate_by_category_id params[:category],
  :page => params[:page], :per_page => 10,
  :order => 'posts.created_at DESC'

我明白了

 NoMethodError in News articlesController#category

undefined method `find_all_by_category' for #<Class:0x103cb05d0>

我能做些什么来解决这个问题?

4

2 回答 2

2

怎么样:

@news_articles = NewsArticle.paginate(:conditions => { :category_id => params[:category_id].to_i }, :page => params[:page], :per_page => 10, :order => 'posts.created_at DESC')

您是否将类别 ID 传递为params[:category]or params[:category_id]?如果你不确定你可以debug(params)在你的视图中。

于 2009-11-11T01:31:21.613 回答
1

我会添加命名范围并将它们与分页一起使用:

class Post < ActiveRecord::Base
  ..
  named_scope :newest, :order => 'posts.created_at DESC'
  named_scope :by_category, lambda { |category_id| { 
    :joins => :categories,
    :conditions => ['categories.category_id = ?', category_id]
  } }
end

@news_articles = NewsArticle.newest.by_category(params[:category]).paginate(
  :page => params[:page], :per_page => 10
  )
于 2009-11-11T07:30:03.697 回答