Coda Chang Coda Chang - 4 months ago 16
Ruby Question

Rails5 add references to create one to many

I create two models call

Restaurant
and
menu
, and Restaurant has_many Menu.
I create Menu by typing

rails g model Menu name restaurant:references


But I found out I can't create Menu by type
Menu.create(name: "test1")


m1 = Menu.create(name: "test1")
(0.2ms) BEGIN
(0.2ms) ROLLBACK
=> #<Menu id: nil, name: "test1", restaurant_id: nil, created_at: nil, updated_at: nil>


Then I checked the
migration
and
schema
, in Rails5 migration the
references
become this

#Menu migration
...
t.references :restaurant, foreign_key: true


I thought in Rails4, it would be somthing like

t.references :restaurant, index: true


Is that the reason I could not create meun?

Update



Here is migration file

class CreateMenus < ActiveRecord::Migration[5.0]
def change
create_table :menus do |t|
t.string :name
t.references :restaurant, foreign_key: true

t.timestamps
end
end
end

Answer

You can't create the menu because your migration includes a foreign key constraint on restaurant_id, meaning a menu can't be created without a restaurant (similarly a restaurant can't be destroyed if associated menus exist). If this is your intent, you'll need to either provide a valid restaurant_id when creating the menu or create it through the association on restaurant

@restaurant.menus.create(name: 'test1')

If you don't need the foreign key constraint, modify the migration and remove the :foreign_key option. If doing this, set the :index option to true.

Comments