Ruby on Rails Associations

Posted by Eef on Stack Overflow See other posts from Stack Overflow or by Eef
Published on 2010-05-12T14:11:05Z Indexed on 2010/05/12 14:14 UTC
Read the original article Hit count: 280

Hey all,

I am starting to create my sites in Ruby on Rails these days instead of PHP.

I have picked up the language easily but still not 100% confident with associations :)

I have this situation:

User Model

has_and_belongs_to_many :roles

Roles Model

has_and_belongs_to_many :users

Journal Model

has_and_belongs_to_many :roles

So I have a roles_users table and a journals_roles table

I can access the user roles like so:

user = User.find(1)
User.roles

This gives me the roles assigned to the user, I can then access the journal model like so:

journals = user.roles.first.journals

This gets me the journals associated with the user based on the roles. I want to be able to access the journals like so user.journals

In my user model I have tried this:

def journals
  self.roles.collect { |role| role.journals }.flatten
end

This gets me the journals in a flatten array but unfortunately I am unable to access anything associated with journals in this case, e.g in the journals model it has:

has_many :items

When I try to access user.journals.items it does not work as it is a flatten array which I am trying to access the has_many association.

Is it possible to get the user.journals another way other than the way I have shown above with the collect method?

Hope you guys understand what I mean, if not let me know and ill try to explain it better.

Cheers

Eef

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord