0

i have following 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, looks good. I'me trying to get all NewsArticle's from category

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

and i see

 NoMethodError in News articlesController#category

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

what can i do to solve this problem?

Alexey Poimtsev
  • 2,845
  • 3
  • 35
  • 63

2 Answers2

2

How about:

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

Are you passing the category id as params[:category] or params[:category_id]? If you're not sure you can debug(params) in your view.

bensie
  • 5,373
  • 1
  • 31
  • 34
1

I would add named scopes and use them with 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
  )
Casper Fabricius
  • 1,159
  • 9
  • 20
  • looks much better :)) thanks :) but unfortunately posts cannot be found if category model is under friendly_id (http://github.com/norman/friendly_id) :( PS: small correction of your example - :conditions => ['categories.id = ?', category_id] – Alexey Poimtsev Nov 11 '09 at 07:51
  • I have updated your example a little and now it works fine @category = Category.find params[:category] @news_articles = NewsArticle.newest.by_category(@category.id) ..... – Alexey Poimtsev Nov 11 '09 at 08:50