Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails active record has_many foreign key after custom function

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().

like image 368
sadaf Avatar asked Aug 30 '16 20:08

sadaf


People also ask

What is the difference between Has_one and Belongs_to?

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.

What is a foreign key in active record?

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.

How does foreign key work in Rails?

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 in Ruby on Rails?

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.


1 Answers

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.

like image 136
RoM4iK Avatar answered Oct 06 '22 22:10

RoM4iK