Rails active record has_many foreign key after user function

Consider the following models

class User < AR has_many :resources end class Resource < AR belongs_to :user end 

I have a requirement when a foreign key is saved after applying some function to it. Thus, the value of user_id in the resource table does not match the identifier in the users table, but it can be calculated again with id.

How to define an association? Say the dummy_func () function.

+7
ruby-on-rails activerecord associations has-many
source share
3 answers

Since belongs_to returns an instance of the class instead of association, you can define methods in the Resource class

 class Resource < ApplicationRecord def user User.find(user_id) end def user=(user) user_id = user.id end end 

Similarly, for has_many result can be achieved by creating a common relationship in the resources method

 class User < ApplicationRecord def resources Resource.where(user_id: id) end end 

So, if you use this code, you can replace any identifiers in the Resource model, and the behavior will be exactly the same as in belongs_to (maybe there is some difference in depths). And you can achieve very similar behavior in the User model by writing methods yourself.

+3
source share

Perhaps you can use the callback to somehow change the current user_id before saving: callbacks .

I would suggest something like: before_save or something like that, where you define how you want the user_id to be changed in the resource table, and then also the way to decrypt it.

Perhaps you can use a cryptographic stone to encrypt and decrypt your attribute, for example attr-encrypted .

Hope this helps a bit!

+2
source share

In the User model, you can override the installer. If you want to encrypt and decrypt the user ID (using attr_encrypted) ...

You can try something like this:

 attr_encrypted :id, key: ENCRYPTION_KEYS[:value] def id=(value) send("encrypted_value=", encrypt(:id, value)) instance_variable_set(:@id, value) end 

Then you can create a method that decrypts the identifier

 def decrypted_id decrypt(:id, encrypted_value) end 

Now that the user is created, the database will set the identifier as usual. But it will also create an encrypted value that stores the identifier as an encrypted identifier. You can use this encrypted value for your application to keep the database secret code in the interface.

Here is an example in the console ...

Console example

+2
source share

All Articles