I have three tables: users , members , projects . Middle - a join table expressing a through passage between two other tables; and it has some attributes of interest, including join_code and activated .
More simply:
class User < ActiveRecord::Base has_many :members has_many :projects, :through => :members end class Member < ActiveRecord::Base belongs_to :user belongs_to :project # has a column called join_code # has a column called activated # Note that this class can be thought of as "membership" end class Project < ActiveRecord::Base has_many :members has_many :users, :through => :members end
Purpose . For a specific user, I want to receive a request that will receive all the projects, and only download the entries of the participants who associate these projects with the user.
So far I have this method in user.rb that executes the request:
def live_projects self.projects.order("projects.name").includes(:members).where(:members => {:join_code => nil, :activated => true}) end
But this is not enough. I would like to do this in the view code:
<% current_user.live_projects.each do |project| %> <li project_id="<%= project.id %>"> <% member = project.member %> (Do something with that member record here) <%= project.name %> <% end %> </li> <% end %>
Here, as a rule, I will have project.members , but in my context, I'm only interested in this entry alone , which refers to the user.
Here is what I think raw SQL should look like
select projects.*, members.* from projects inner join members on projects.id = members.project_id where members.user_id = X and members.join_code is null and members.activated = 't';
How to do it in Arel (or ActiveRecord)?