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 

좋아, 좋아 보인다. 나는 모든 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> 

이 문제를 해결하려면 어떻게해야합니까?

답변

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) 아래에 있으면 게시물을 찾을 수 없습니다. ( 추신 : 작은 예제 수정 - : 조건 => [ 'categories.id =?', category_id] –

+0

있습니다. 귀하의 예제를 조금 업데이트했는데 이제는 잘 작동합니다. @category = category.find params [: category] @news_articles = NewsArticle.newest.by_category ..... –

2

방법에 대해 :

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

당신이 params[:category] 또는 params[:category_id] 같은 범주 ID를 전달하고 있는가? 확실하지 않은 경우 debug(params)을 (를) 볼 수 있습니다.

+0

더 나은,하지만 지금은 다음과 같습니다 내가 PARAMS [같은 카테고리의 ID를 전달 해요 "이러한 열은 posts.category_id"범주를 ] –

+0

로 전환 시도 : order => : category_id – bensie