I am doing a pilot eval of Rails for my company. We’re using it to build
a reporting module on top of a mysql database which is currently
populated by a ASP.NET application.
One thing I am wondering about is the utility of ActiveRecord
associations, and whether I am missing some simple trick in their use.
Assume I have a User and a Post. Users can have many posts, and Posts
have characteristics like a datestamp, rating, word count, deleted flag,
etc.
While it is beautifully easy to do john.posts and get all of John’s
posts, what I almost always need to do is get john.posts(not_deleted and
post_date=today) or something like that.
Granted, I’ve figurd out how it can be done e.g. Posts.find(john,
not_deleted, date…) but by the time I’m done it seems like all I’m
getting from ActiveRecord is a less top-heavy interface for SQL result
sets, which is a nice thing for sure. But, I’m feeling a bit let down as
the need to select associated objects with conditions beyond just the
association is pervasive, which means I am back to writing lots of
get_foo methods and doing sql construction.
While it is beautifully easy to do john.posts and get all of John’s
posts, what I almost always need to do is get john.posts(not_deleted and
post_date=today) or something like that.
You can define a :conditions attribute when you find associated objects,
or on the association call itself.
This way john.posts will always conform to the defined conditions. And
if you want all posts, regardless of not_deleted status, you can call
john.all_posts. Just note that you have to tell it the class_name and
foreign_key of the association since it can’t be directly inferred form
“all_posts”.
Alex- thanks for that tip, that fills in some big gaps. However, I ran
into one snafu:
Alex W. wrote:
Cw K. wrote:
While it is beautifully easy to do john.posts and get all of John’s
posts, what I almost always need to do is get john.posts(not_deleted and
post_date=today) or something like that.
You can define a :conditions attribute when you find associated objects,
or on the association call itself.
This way john.posts will always conform to the defined conditions. And
if you want all posts, regardless of not_deleted status, you can call
john.all_posts. Just note that you have to tell it the class_name and
foreign_key of the association since it can’t be directly inferred form
“all_posts”.
While it is beautifully easy to do john.posts and get all of John’s
posts, what I almost always need to do is get john.posts(not_deleted and
post_date=today) or something like that.
You can define a :conditions attribute when you find associated objects,
or on the association call itself.