Rails - Find all projects of a user

ruby, ruby-on-rails, ruby-on-rails-3

Solution

The error is probably be due to the fact that you aren't following Rails' naming convention.

- Models should have names in singular form: `ProjectUser` rather than `ProjectsUsers`.

- If you aren't planning to save any additional data in the `ProjectUser` model, you'd be better off just using a normal `has_and_belongs_to_many` relation. In other words: no "join model", just a join table named `projects_users`.

So either you do this:

class User < ActiveRecord::Base
    has_and_belongs_to_many :projects
end

class Project < ActiveRecord::Base
    has_and_belongs_to_many :users
end

Or you do this:

class User < ActiveRecord::Base
    has_many :project_users
    has_many :projects, through: :project_users
end

class Project < ActiveRecord::Base
    has_many :project_users
    has_many :users, through: :project_users
end

class ProjectUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :project
end

In both cases you can do this: `user.projects` and `project.users`

Problem

I started to learn Rails a few days ago and also have not much experience with Ruby too. The problem with me now is trying to find all the projects of a certain user, given the relationship below. User Model ``` class User < ActiveRecord::Base has_many :projects_users has_many :projects, :through => :projects_users attr_accessible :email, :firstname, :id, :lastname, :password, :username, :password has_secure_password end ``` Project Model ``` class Project < ActiveRecord::Base has_many :projects_users has_many :users, :through => :projects_users attr_accessible :date_created, :id, :name end ``` Project_User Model ``` class ProjectsUsers < ActiveRecord::Base belongs_to :project belongs_to :user end ``` My attempt so far is: ``` @projectuserid = ProjectsUsers.find(:all, :conditions => "user_id=#{session[:user_id]}") @projects = Project.all(@projectuserid) ``` But it seems like `@projectuserid` is an array itself so the query doesn't work. I know it could be achieved in one line of code for this HABTM relationship model, but still I have so little knowledge about Rails. Another approach of mine looks like this, but a blank result returned: ``` @projects = Project.find :all, :conditions => "id in (select distinct project_id from projects_users where user_id=#{session[:user_id]})" ```

Original source