Frage

The goal

Relating users table with users_photos table.

The problem

I just don't know how to do.

The scenario

This is the command line that I express to create the users_photos table:

rails generate migration CreateUsersPhotos image_url:string thumbnail_url:string user:references

It creates the index user_id, but there's not any foreign key. I heard about that Rails don't create foreign keys because SQLite doesn't offers support for that feature. It proceeds, right? Maybe foreigners could help, right?

The point is: when I generates the migration and do rake db:migrate, any model is created. In other words, just the table is created and I can't interact with the model to add foreign key to it.

After all, what's the question?

  1. When I run rake db:migrate, it doesn't create the model. Why?
  2. How can I add foreign key to users_photos? I need to delete user_photo's entry when a user is deleted.
War es hilfreich?

Lösung

  1. Migrations do not create model. Run rails generate model UserPhotos ... to create both migration and the model. Otherwise you need to create your model manually. Do not worry about foreign keys, rails handle association well enough without them.

  2. I personally prefer to do user_id:integer in migration, but the way you have it all should work. If you want new model records to be deleted together with their parent, use

    # User model
    has_many :user_photos, dependent: :destroy`
    

Andere Tipps

Migrations and models. Migrations are related to database schema: tables, rows and all that stuff. So, rake db:migrate won't create any models for you. You need to do it by yourself. For example, like this:

rails generate model User name:string

It will generate appropriate model and migration for you (that migration contains code to generate 'users' table).

Foreign keys. Yes, you're right. Rails don't create foreign keys. There're couple of ways of doing that anyway (raw sql). But these are bad options. What you can do, is to put that kind of logic (deletion of associated records) inside of model. Here's a link to Rails associations guide. You can declaratively state deletion of associated records by something like this:

class User < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

You can assign foreign key like user has many posts but in post it is saved as author_id

class User < ActiveRecord::Base
has_many :posts, dependent: :destroy, :foreign_key => :author_id
end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top