Reputation: 5001
Relating users
table with users_photos
table.
I just don't know how to do.
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.
rake db:migrate
, it doesn't create the model. Why?users_photos
? I need to delete user_photo
's entry when a user is deleted.Upvotes: 0
Views: 267
Reputation: 121
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
Upvotes: 0
Reputation: 1510
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
Upvotes: 1
Reputation: 44715
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.
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`
Upvotes: 1