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]})"
The error is probably be due to the fact that you aren’t following Rails’ naming convention.
ProjectUserrather thanProjectsUsers.ProjectUsermodel, you’d be better off just using a normalhas_and_belongs_to_manyrelation. In other words: no “join model”, just a join table namedprojects_users.So either you do this:
Or you do this:
In both cases you can do this:
user.projectsandproject.users