many_to_many、STIとページ付けます
-
19-09-2019 - |
質問
私は、次のコードしている。
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カテゴリからすべての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>
私はこの問題を解決するために何ができるのでしょうか?
解決
私は名前のスコープを追加しての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
)
他のヒント
いかがます:
@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)
ことができます。
所属していません StackOverflow