DEV Community

Mary Webby
Mary Webby

Posted on

Photogram Industrial Notes

notes about scaffolds for CRUD & generating a model

  • The question you have to answer now is: for each of these tables, do you want to generate a scaffold or do you just want to generate a model? How do we figure that out?

If I will need routes and controller/actions for users to be able to CRUD records in the table, then I probably want to generate scaffold. (At least some of the generated routes/actions/views will go unused. I need to remember to go back and at least disable the routes, and eventually delete the entire RCAVs, at some point; or I risk introducing security holes.)

If the model will only be used on the backend, e.g. by other models, then I probably want to generate model. For example, a Month model where I will create all twelve records once in db/seeds.rb does not require routes, MonthsController, app/views/months/, etc.

foreign keys in migrates & models

  • any times you are specifying the forgein_key within a migrate file, you need to also make sure to go and change it in the model as well. so here is our migrate file
class CreateComments < ActiveRecord::Migration[7.0]
  def change
    create_table :comments do |t|
      t.references :author, null: false, foreign_key: { to_table: :users }
      t.references :photo, null: false, foreign_key: true
      t.text :body

Enter fullscreen mode Exit fullscreen mode
  • and we are specifically looking at the foreign_key: { to_table: :users } part of this. and you can see we specified that the users table is going to be what the author is referring to.

  • so now in our models, we can go into comment.rb, and in here we can add in the specific classname for the author

class Comment < ApplicationRecord
  belongs_to :author, class_name: "User"
  belongs_to :photo
Enter fullscreen mode Exit fullscreen mode

Raghu: "So basically for every foreign_key, there should be a belongs_to. For every belongs_to, there should be a has_many."<

rails db:drop will delete your entire database, rails db:rollback will undo your last migration<

will need to keep all the migration files to see all the history of changes and

Top comments (0)