Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After <a href="https://stackoverflow.com/users/985241/rmagnum2002">rmagnum2002</a> made me realize that I could use foreign_key parameter here, I started googling "rails multiple foreign key to same table", stumbled upon a bunch of outdated SO answers that didn't work and finally found <a href="http://www.emreakkas.com/ruby-on-rails/rails-multiple-columns-to-the-same-tables-key" rel="nofollow noreferrer">this article</a> which helped me write the code that works.</p> <p>So, this is the relation that I put into my JSymbol model:</p> <pre><code>belongs_to :created_by, :class_name =&gt; User, :foreign_key =&gt; "created_by_id" belongs_to :updated_by, :class_name =&gt; User, :foreign_key =&gt; "updated_by_id" </code></pre> <p>and this one is from Users model:</p> <pre><code>has_many :occurances_as_created_by, :class_name =&gt; JSymbol, :foreign_key =&gt; "created_by_id" has_many :occurances_as_updated_by, :class_name =&gt; JSymbol, :foreign_key =&gt; "updated_by_id" </code></pre> <p>I didn't have to add anything in my action method, and this is what I put in the view:</p> <pre><code>&lt;%= j_symbol.created_by.username %&gt; &lt;%= j_symbol.updated_by.username %&gt; </code></pre> <p>This is what happens in SQL if anyone is interested (which means it actually does it through separate select queries instead of joins so I might yet keep looking for a better solution):</p> <pre><code>JSymbol Load (0.3ms) SELECT "j_symbols".* FROM "j_symbols" JSymbolType Load (0.3ms) SELECT "j_symbol_types".* FROM "j_symbol_types" User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 LIMIT 1 User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 LIMIT 1 CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 LIMIT 1 CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 LIMIT 1 Rendered j_symbols/index.html.erb within layouts/j_symbols (7.8ms) CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 8 LIMIT 1 </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.
    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