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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x