0

我有以下代碼MANY_TO_MANY,STI,將分頁

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 

OK,看起來不錯。 I'me試圖從類別

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

所有NewsArticle的,我看到

NoMethodError in News articlesController#category 

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

我能做些什麼來解決這個問題?

回答

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 
) 
+0

看起來好多了:))謝謝:)但不幸的帖子無法找到,如果類別模型是在friendly_id(http://github.com/norman/friendly_id):( PS:你的例子小修正 - :conditions => ['categories.id =?',category_id] – 2009-11-11 07:51:11

+0

我有更新你的例子有點現在它工作正常 @category = Category.find params [:category] ​​ @news_articles = NewsArticle.newest.by_category(@ category.id)..... – 2009-11-11 08:50:17

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)

+0

更好,但是現在看起來「沒有這樣的列:posts.category_id」 我傳遞類別ID爲PARAMS [:類別] – 2009-11-11 07:18:03

+0

嘗試切換到:order =>:category_id – bensie 2009-11-11 16:22:45