DEV Community

austinmei5
austinmei5

Posted on

Scaffold Tutorial

When considering Draft Resource vs. Scaffold, think about which RCAVs we need for our app. (Create, edit, update, destroy actions).

  1. Command to generate: "rails generate scaffold task text:string status:string owner:references"

  2. (cont.) Using 'owner:references' instead of 'owner_id:string' initializes the 'owner' column as a foreign key column in the database.

  3. In the model migration file, update any default values.

  4. 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.

  5. Since we used :owner instead of :user, we need to add to the foreign key: 'foreign_key: { to_table: :users }'

  6. (cont.) If we do not do this step, the migration will fail.

  7. In the 'tasks' model, we also need to update the belongs_to relation: 'belongs_to :owner, class_name: "User"'.

  8. (cont.) In the users model, we add the following association: 'has_many :own_tasks, class_name: "Task", foreign_key: "owner_id"'.

  9. (cont.) belongs_to should always have a matching has_many association.

  10. Repeat for any other models in the app.

Top comments (0)