When considering Draft Resource vs. Scaffold, think about which RCAVs we need for our app. (Create, edit, update, destroy actions).
Command to generate: "rails generate scaffold task text:string status:string owner:references"
(cont.) Using 'owner:references' instead of 'owner_id:string' initializes the 'owner' column as a foreign key column in the database.
In the model migration file, update any default values.
Typically, we might also want to add 'index: true' to the :owner column in the migration file. However, this should be set to true by default in current versions of Rails.
Since we used :owner instead of :user, we need to add to the foreign key: 'foreign_key: { to_table: :users }'
(cont.) If we do not do this step, the migration will fail.
In the 'tasks' model, we also need to update the belongs_to relation: 'belongs_to :owner, class_name: "User"'.
(cont.) In the users model, we add the following association: 'has_many :own_tasks, class_name: "Task", foreign_key: "owner_id"'.
(cont.) belongs_to should always have a matching has_many association.
Repeat for any other models in the app.
Top comments (0)