1

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 
0

1 Answer 1

2

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
2
  • thank you. Can you tell one more thing? I want one user to be assigned to rate another user. So I need table with userid, userid2, ratings: rails g scaffold User name && rails g scaffold UserReview ratings:integer user:references user2:references.
    – VMG
    Jul 8, 2021 at 11:46
  • 1
    Sure, in that case your columns would be like rate_user_id, rated_by_user_id, you'd have to create the migration, with placeholder values through the rails command and then modify it as you need in the migration file, see the updated answer @VMG. Jul 8, 2021 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.