I would like to define a polymorphic table. My problem being that one table's primary_key is of type uuid(string)
and the other id(integer)
. I thought maybe having a model_able_id
and a model_able_uuid
varying depending on the model_type
but i cannot figure that out and it would probably break tons of activerecord features for polymorphic.
Some other things i have thought of would be to use STI, but i'm still confused, and, of course, i could migrate ids to uuids and that'd sort me out (but i'd rather not).
Specify the type for the (polymorphic) foreign key in the options. Change :string
to :uuid
if required.
create_table :table_name do |t|
t.references :target, type: :string, polymorphic: true, null: false
end
Then both string and integer target_id
s are acceptable.
Check the API docs .
Was facing same issue, there is no official solution yet, these two issues are open in rails repo about this:
https://github.com/rails/rails/issues/33407
https://github.com/rails/rails/issues/33525
There is a suggestion in one of these issues , it didn't work for me(it was generating both joins, the default one generated by rails which causes failure and one which i defined).
I ended up not using association at all, i defined a method to get the actual records properly with a custom query. I didn't need dependent: destroy
otherwise i could have defined a before_destroy method too.
Hope it helps someone.
I had exactly the same problem. My solution modifies the type of the _id
field to string.
def change
add_reference :ratings, :rater, polymorphic: true, index: true
change_column :ratings, :rater_id, :string
end
I hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.