views:

104

answers:

2

Hi, 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?

+2  A: 

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
better, but now it looks like "no such column: posts.category_id"i'm passing category id as params[:category]
Alexey Poimtsev
Try switching to :order => :category_id
bensie
+1  A: 

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
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
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