我有一个简单的rails 7应用程序,我可以在其中创建一个每周菜单。然后,用户可以选择他们想要的星期几。
我在设计和制作上遇到了点麻烦。这是我到目前为止所拥有的:
rails generate model WeeklyMenu monday:references tuesday:references wednesday:references thursday:references friday:references saturday:references sunday:references
rails generate model Day lunch:references brunch:references dinner:references
rails generate model Meal title:string description:text
字符串
第一个月
class WeeklyMenu < ApplicationRecord
belongs_to :monday, class_name: 'Day'
belongs_to :tuesday, class_name: 'Day'
belongs_to :wednesday, class_name: 'Day'
belongs_to :thursday, class_name: 'Day'
belongs_to :friday, class_name: 'Day'
belongs_to :saturday, class_name: 'Day'
belongs_to :sunday, class_name: 'Day'
end
型app/models/day.rb
个
class Day < ApplicationRecord
belongs_to :lunch, class_name: 'Meal'
belongs_to :brunch, class_name: 'Meal'
belongs_to :dinner, class_name: 'Meal'
end
型app/models/meal.rb
个
class Meal < ApplicationRecord
end
型
这是我计划如何创建它,但我得到和错误与dinner
,我不知道为什么,与午餐和早午餐,我没有问题:
v1 = Meal.create(title: 'Meal 1', description: 'Desc 1')
v2 = Meal.create(title: 'Meal 2', description: 'Desc 2')
v3 = Meal.create(title: 'Meal 3', description: 'Desc 3')
day2 = Day.create(lunch: v1) # fine
day3 = Day.create(lunch: v1, brunch: v2) # fine
day1 = Day.create(lunch: v1, brunch: v2, dinner: v3) # error
day4 = Day.create(cena: v3, brunch: v2, lunch: v1) # error
WeeklyMenu.create(
monday: day1,
tuesday: day2,
wednesday: day1,
thursday: day2,
friday: day3
)
型
我得到的错误:
Day Create (0.7ms) INSERT INTO "days" ("lunch_id", "brunch_id", "dinner_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["lunch_id", 6], ["brunch_id", 4], ["dinner_id", 5], ["created_at", "2023-07-03 02:21:40.793290"], ["updated_at", "2023-07-03 02:21:40.793290"]]
TRANSACTION (0.1ms) rollback transaction
/Users/dev/.rvm/gems/ruby-3.2.0/gems/sqlite3-1.6.3-arm64-darwin/lib/sqlite3/database.rb:152:in `initialize': SQLite3::SQLException: no such table: main.dinners (ActiveRecord::StatementInvalid)
/Users/dev/.rvm/gems/ruby-3.2.0/gems/sqlite3-1.6.3-arm64-darwin/lib/sqlite3/database.rb:152:in `initialize': no such table: main.dinners (SQLite3::SQLException)
型
1条答案
按热度按时间z9ju0rcb1#
午餐和早午餐我没问题
day2 = Day.create(lunch:v1)# fine day3 = Day.create(lunch:v1,早午餐:v2)# fine
这并不好,因为Rails的失效开放设计。让我们来看看day2和day3:
day2.valid2? => false
的。然后是示例中的最后一条错误消息:
SQLite3::SQLException: no such table: main.dinners
。Rails尝试引用不存在的dinners
表。这是因为迁移的定义方式:字符串
此架构无法按预期工作。您可以使用
<meal>_id
整数,如下所示:型
使用外键:
型