Many_to_Many, STI und werden paginieren
-
19-09-2019 - |
Frage
Ich habe den folgenden Code
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, sieht gut aus. Ich versuche, alle Newsarticle aus der Kategorie zu bekommen
@news_articles = NewsArticle.paginate_by_category_id params[:category],
:page => params[:page], :per_page => 10,
:order => 'posts.created_at DESC'
Und ich sehe
NoMethodError in News articlesController#category
undefined method `find_all_by_category' for #<Class:0x103cb05d0>
Was kann ich tun, um dieses Problem zu lösen?
Lösung
Ich würde benannte Scopes hinzufügen und sie mit Paginat verwenden:
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
)
Andere Tipps
Wie wäre es mit:
@news_articles = NewsArticle.paginate(:conditions => { :category_id => params[:category_id].to_i }, :page => params[:page], :per_page => 10, :order => 'posts.created_at DESC')
Übergeben Sie die Kategorie -ID als params[:category]
oder params[:category_id]
? Wenn Sie nicht sicher sind, dass Sie es können debug(params)
Aus Ihrer Ansicht.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow