Add association_primary to has_and_belongs_to_many#307
Conversation
imdrasil
left a comment
There was a problem hiding this comment.
Great job 👍 I'd only adjust one tiny thing. This feature definitely will be useful
|
Would you like me to make a spec? I haven't dug into your tests so idk what's their but i am sure this spec would be similar to whatever spec tests 'association_foreign'. |
|
@andrewc910 It would be great |
|
Okay, i think i did it. All i did was add I also change the Finally i added a comment which i plan to remove. Just wanted to mark it and see your thoughts. I couldn't quite understand the method |
|
Problem: When using Fix: This newest commit changes New Problem: **Note:**I don't believe there are explicit tests for these methods. This was something i discovered when refactoring some controllers. |
| { | ||
| foreign_field => obj.attribute(primary_field), | ||
| association_foreign_key => rel.primary, | ||
| association_foreign_key => |
There was a problem hiding this comment.
association_primary ? rel.attribute(association_primary.not_nil!) : rel.primary
| _primary = primary_field | ||
| jt = join_table! | ||
| q = query.join(jt, type: type) { Q.c(_primary) == c(_foreign) }.join(T, type: type) do | ||
| # TODO: Replace `T.primary` with `association_primary_key`? |
|
Yeah, my initial suggestion does work because |
First, let me say if this already exists and I am using jennifer wrong, please just let me know!
What does this PR do?
Adds
association_primarytohas_and_belongs_to_many. Currently, the query is built by defaulting to the primary key of the other table withT.primary. This allows users to define a different column, likeuuid, while keepingidas the primary key for the table.Any background context you want to provide?
Right now i have an
App& aUsermodel. They are connected byhas_and_belongs_to_manywith the join table beingapps_users.App psuedo sql table:
apps_userssql table:Right now when i do:
It throws a bad query error. The sql looks like this:
Notice the
apps_users.app_id = apps.id. A proper query would look like:In the user class i can do
association_foreign: :uuidwhich is obviously wrong but changes the sql query to:Almost right. That's what led me down this rabbit hole. With this PR, i can change the above to
association_primary: :uuidRelease notes
Please fill the corresponding section regarding this pull request notes below instead of modifying
CHANGELOG.mdfile. Please remove all redundant sections before posting request.Model
Adds
association_primarytohas_and_belongs_to_manyrelation to allow specifying a separate column for querying other than the primary key columnOther
I am not too happy with how
association_primary_keycame out inManyToManyand would love to see a more elegant solution.