Understanding Rails ActiveRecord association or relationship



Lets say we are trying to define a relationship user and product in ActiveRecord you need to :-

1. Define association on both sides of your model. For example, a user can have many products, you would in turn define relationship as follows :-






We have the association parameter on both sides of our model. This also means product table will need a column called 'user_id'- which stores relationship to a specific user who owns this product.

User model has a marker called 'has_many'

Product model has a marker called 'belongs_to' - belongs_to also requires that you create a new column called user_id field in your database.

Please note, that i use 'Product' and not the plural table name auto created by rails which always pluralized an object for you.

2. create a new database migration - it might involve creation of a new field for example user_id to hold data for an association. We might run the following command

rails generate migration add_user_id_to_product user_id :string

3. run rake db:migration

4. Use rails console to test out this association

Comments

Popular posts from this blog

OpenCover code coverage for .Net Core

ionic2 cordova build android - Unable resolve gradle 2.2.3

Using Custom DLL with IronPython / Scripts