Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4ruby-on-rails-3.1

Ruby On Rails scaffold need to include foreign keys?


I'm learning the basics of ruby on rails and I want to make some simple queries but I have a doubt:

I will have these models:

class Client < ActiveRecord::Base
  has_one :address
  has_many :orders
  has_and_belongs_to_many :roles
end

class Address < ActiveRecord::Base
  belongs_to :client
end

class Order < ActiveRecord::Base
  belongs_to :client, counter_cache: true
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :clients
end

Now, I will use scaffold to generate all the things, and I want to know if I have to directly put the foreign keys in the scaffols, like:

rails generate scaffold Adress street:string number:integer client_id:integer

Or when I make those associations and then migrate my db they will be implicit?

I don't know if I explain myself in the best way.

Thanks


Solution

  • Yep, there is no reference. You need to either pass the client_id or a reference to Client model, e.g:

    rails generate scaffold Address street:string number:integer client_id:integer:index 
    

    or

    rails generate scaffold Address street:string number:integer client:references