Consider following models
class User < AR
has_many :resources
end
class Resource < AR
belongs_to :user
end
I have a requirement where the foreign key is saved after applying some function on it. So the value of user_id in resources table does not match id in users table but it can be calculate again from id.
How can I define the association? Let's say that function is dummy_func().
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.
In Rails 5, adding foreign key constraints was added to have the database protect the integrity of associated data. Once a foreign key constraint is defined, your database will not allow you to remove records that are required by other tables.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Since belongs_to
returns class instance instead of association, you can define methods in Resource
class
class Resource < ApplicationRecord
def user
User.find(user_id)
end
def user=(user)
user_id = user.id
end
end
Similar for has_many
result in user can be achieved by creating common relation in resources
method
class User < ApplicationRecord
def resources
Resource.where(user_id: id)
end
end
So, if you use this code, you can replace any ids in Resource
model, and behavior will exactly same as in belongs_to
(Maybe there is some difference in depths). And you can achieve very similar behavior in User
model, by writing methods by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With