Backward associations

hi everyone,
my situation is describes as:

User has_many Blog
Blog has_many BlogPost

BlogPost belongs_to Blog
Blog belongs_to User

now, to “bridge” User with Post I wrote in User model:

has_many :blog_posts, :through => :blogs, :source => :posts

and so far it works.

to bridge BlogPost with User (author) I wrote in BlogPost model:
delegate :user, :to => :blog

the problem is, since there’s no belongs_to :through, I need to find a
better AR compliant way to bridge BlogPost with User, since I have to
use a counter_cache field on User model that contains the number of
BlogPost he made.

of course I can write my callbacks to handle this situation, but I
feel like reinventing the wheel.

somebody got some tips to share?

thanks

On 20 Jul 2008, at 16:11, Claudio P. wrote:

now, to “bridge” User with Post I wrote in User model:
use a counter_cache field on User model that contains the number of
BlogPost he made.

Have you tried has_one :through ?

Fred

I forgot to add that yes, I may duplicated the user_id field in
BlogPost, but I’m not sure it’s the better way since there’s already
Blog that contains such information.

Would make sense however if there are many users that can write
BlogPost in another person’s Blog, but this is not the case.

hi Frederick,
yes, I’ve tried some hours ago, but it failed, I’ve tried again now
and it seems to work, maybe there was an error somewhere.

thanks.

oh uhm… I’m messing up things, sorry for that (fast experimenting),
no, it doesn’t work:

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column
‘blogs.blog_id’ in ‘where clause’: SELECT users.* FROM users
INNER JOIN blogs ON users.id = blogs.user_id WHERE
((blogs.blog_id = 1))