ActiveRecord allows an association to be extended, as in:

module FindWeeklyExtension
def weekly(start)
where("created_at > :t1 and created_at < :t2",
:t1 => start,
:t2 => start + 7.days
)
end
end

class Author
has_many :posts, :extend => FindWeeklyExtension
end

Over time, though, classes might start to include many modules:

class Author
# several modules

has_many :posts, :extend => [...]
end

You might notice that you only need an extension or module to exist in
one particular context:

module WeeklyDigest
def weekly_posts(start)
posts.weekly(start)
end
end

So it'd be cleaner not to have that in the class, and instead to do
something like this:

# Author
class Author
has_many :posts # we refactored :extend => FindWeeklyExtension ...
end

module WeeklyDigest
def weekly_posts(start)
posts.extend FindWeeklyExtension # ... and moved it here
posts.weekly(start)
end
end

However, this doesn't work:

NoMethodError: undefined method `where' for #<Array:
0x00000007d0e970>

So, is there a good way to extend an association, but only for a
specific instance's association?

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedJan 19, '12 at 9:56a
activeJan 19, '12 at 9:56a
posts1
users1
websiterubyonrails.org
irc#RubyOnRails

1 user in discussion

John Feminella: 1 post

People

Translate

site design / logo © 2021 Grokbase