简体   繁体   中英

Ruby on Rails - rails g scaffold foreign key

Im new to ruby and I want ot create database with table User, Role and user Role. And my question is should I use scaffold or something else? And how to add autoincrement id in this tables? And how to add foreign key?

rails g scaffold User name:string surname:string  && rails generate scaffold Role name:string id:integer 

Should I use scaffold or something else?

You can use a scaffold, if what you need is all the files and changes in your project related to that specific table/model. A scaffold will add assets, models, controllers, and even tests. If you feel you don't need it, you can create a single migration which can handle the table creation in your database and that's all. If in the other hand, you need more than that, you can create a model ( rails g model ... ), and so on, and so forth.

And how to add autoincrement id in this tables?

By convention, Rails will add an id column in your table, unless specified otherwise. Depending on your database, it'll will use the AUTO INCREMENT clause, or a SERIAL if using Postgres. As it supports multiple relational database management systems, there are a lot of options for that.

And how to add foreign key?

When creating a scaffold, or a model, or a migration, you can use the references option. In your case If you have a User and UserRole models/tables, it'd look like this:

rails g scaffold User name && rails g scaffold UserRole user:references

You can check the Rails guides about migrations for further information.


Complement for the given question:

class ... < ActiveRecord::Migration[5.0]
  def change
    create_table :... do |t|
      t.references :user_id_rated, references: :users, foreign_key: true
      t.references :rated_by_user_id, references: :users, foreign_key: true
      ...
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM