开发者

How to apply scopes to association through collection?

I have a model Category that has_many :posts. On my index page I iterate over categories and output it something like this:

@ca开发者_如何学编程tegories.each do |category|
  link_to category.title, category

  category.posts.published.limit(4).each do |post|
    link_to post.title, post
  end

end

It works, but published.limit(4) doesn't belong there and I'd like to move it to the controller. How do I do that?

Thanks.


I would create a scope on Post that encapsulated both published and a limit:

class Post < ActiveRecord::Base

  scope :highlights, published.limit(4)

end

And then use it in the view like so:

@categories.each do |category|
  link_to category.title, category

  category.posts.highlights.each do |post|
    link_to post.title, post
  end
end

If you wanted to be able to customize the length of the highlights you could change the scope call to look like this:

scope :highlights lambda { |size| { published.limit(size) } }

and then use it like:

category.posts.highlights(5) 


you can create an object in controller like:

def index
  @published_posts = @categories.collect { |c| c.posts.published.limit(4) }
  # but this will be an array of arrays, so let flatten
  @published_posts = @published_posts.flatten # array of published posts
end

now you can use this variable in your views.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜