Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm afraid ShivamD's answer will not suffice. That would require duplicate <code>Skills</code>, and queries the relevant <code>User.help_requests</code> via relationship, where instead you need an intersection.</p> <p>Not just that, <code>Users</code> who create <code>HelpRequests</code> will already have a <code>has_many</code> relationship. That makes sense.</p> <p>I won't include schema for the <code>HABTM</code> I'm about to suggest (see <a href="http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association" rel="nofollow">here</a>), but I will cover the models. Essentially what you want:</p> <pre><code>skill = Skill.create(name: "My Skill") user.skills &lt;&lt; skill help_request.skills &lt;&lt; skill user.matched_help_requests #&gt; [help_request] </code></pre> <p>Which can be achieved as follows:</p> <pre><code>class User has_and_belongs_to_many :skills def matched_help_requests HelpRequest.joins(:skills).where("skills.id IN(?)", skills.pluck(:id)) end end class HelpRequest has_and_belongs_to_many :skills end class Skill has_and_belongs_to_many :users has_and_belongs_to_many :help_requests end </code></pre> <hr> <p>EDIT: here's the schmea for the <code>HABTM</code>:</p> <pre><code>rails g migration add_skills_join_tables </code></pre> <h3>within migration</h3> <pre><code>def change create_table :skills_users, id: false do |t| t.references :skill t.references :user end create_table :help_requests_skills, id: false do |t| t.references :skill t.references :help_request end add_index :skills_users, [:skill_id, :user_id] add_index :help_request_skills, [:skill_id, :help_request_id] end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload