2

Hi for rails model association, i know i can do this:

For example a model class Page.

class Page < ActiveRecord::Base

 has_many :parts

end

I can do this:

Page.first.parts.find_by_name('body')

Page.first.parts.class actually returns Array. How can it activate methods for Part model? I found the similar post on How do rails association methods work?

My question is that when i try to use memcache to cache the response for parts methods. Then when i call Page.first.parts.find_by_name('body'), it tells me that the Array doesn't have method find_by_name. How do i solve this problem? I need to have the cache as this is one heavily used methods.

class Page
  def parts_with_cache
    Rails.cache.fetch("parts_for_page_#{id}", {:expires_in => 1.minutes}) do 
      parts_without_cache
    end
  end
  alias_method_chain :parts, :cache
end
Community
  • 1
  • 1
Shanison
  • 2,295
  • 19
  • 26

1 Answers1

0

Since you are getting back an array of Parts objects associated to the Page object unfiltered by part name, just do an Array select method on the result set.

body_parts = Page.first.parts.select{ |part| part.name == 'body' }
Ben Evans
  • 98
  • 1
  • 5