0
votes

I've got to define a One-To-Many association in Rails. Like e.g. "Vendor" and "Article" (One vendor has many articles).

Is it necessary to have a foreign key-field "vendor_id:int" in "Article" when scaffolding?

Or is it sufficient to define the associations later within the model-classes of "Vendor" and "Article"?

Means: "Article"-class gets a statement "belongs_to :vendor" and "Vendor"-class gets a statement "has_many :articles".

2

2 Answers

2
votes

Its not necessary to have a foreign_key in article table but you should have. Code to generate the scaffold should be like below

rails g scaffold article vendor:references field1:datatype field2:datatype ...

It will generate a rails migration with the create statement for article table. It will have a foreign_key i.e. vendor_id like below

class CreateArticles < ActiveRecord::Migration[5.1]
  def change
    create_table :articles do |t|
      t.references :vendor, foreign_key: true
      .....other fields

      t.timestamps
    end
  end
end

If you dont want forign_key, you can remove foreign_key from the migration

belongs_to :vendor will be automatically added in the article model.

1
votes

Necessary? No. We can still use the below in rails 5 migrations:

add_reference :article, :vendor, foreign_key: true

but we can also have some controller magic to 'relate' without references. The only issue with this is we will still have to store the relational id somewhere. For example, if you want a reference without foreign key for the index, write the following in the controller for article:

def index
    @vendor = Vendor.find(params[:vendor_id]) if params[:vendor_id]
    ## do stuff with vendor object
end

Is this the correct way to do this? If you absolutely need to avoid using a foreign key then it is one method of achieving the same result. Where you store and send the params for the id relation is up to the developer.