matthewalexander matthewalexander - 3 months ago 7x
Ruby Question

Rails migration t.belongs_to :user, add custom column name seller_id?

I am trying to add seller_id to my items model in a migration by doing the following:

rails g model Item title:string description:text price:bigint status:integer published_date:datetime seller:belongs_to

This didn't work of course...

ultimately I want to see seller_id in my items table, which relates the item model to the user model.

Presently my migration looks like this:

class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.string :title
t.text :description
t.bigint :price
t.integer :status
t.datetime :published_date
t.belongs_to :user, index: true, foreign_key: true
t.timestamps null: false

  1. How can I modify this migration to create a foreign key "seller_id" that relates to the user model.

  2. How can I auto generate a migration that includes edits from 1., from the console? I.E modify the rails g model ... to generate the migration I need.

Huge Thanks!


Just explicitly define what you want in the migration file and add the necessary relation to your model, instead of t.belongs_to you could just use:

t.integer :seller_id, index: true, foreign_key: true

and in your models you could go about this a few ways, if you also want reference your relation as seller on item instances then in the Item class make the relation:

belongs_to :seller, class_name: 'User'

and in the User class:

has_many :items, foreign_key: :seller_id

or if you want to reference it as user from the items then:

belongs_to :user, foreign_key: :seller_id

In terms of editing the generator, that is the default way that a model generator works and in my opinion I like to keep the defaults the way they are. However I do recommend creating your own rails generators or your own rake tasks for when you want to create some custom / special case stuff. For looking at creating your own generator I would point you to the ruby on rails official guide for creating generators to get you started: