我有以下代码
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>
我该怎么做才能解决这个问题?
答案 0 :(得分: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]
或params[:category_id]
?如果您不确定可以在视图中debug(params)
。
答案 1 :(得分:1)
我会添加命名范围并将其与paginate一起使用:
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
)