我的模特
class Event < ApplicationRecord
has_many :event_options
end
class EventOption < ApplicationRecord
belongs_to :event
end
在rails c
中,我可以使用它来创建Event
就好了。
Event.create(name:"Face Painting", active:true)
然而,当我这样做时:
EventOption.create(description:"You give us money. We paint your face.", price: 250.00, name: "People Painting 1", event: 1);
它给我一个回滚错误:
@details={:event=>[{:error=>:blank}]},
@messages={:event=>["must exist"]}>
我只使用event_id
和id
以及:event_id/:event/:id => 1
进行尝试,但由于某些原因,他们都没有让我提供{{1}的链接创建时EventOption
。
有任何线索吗?
答案 0 :(得分:2)
我感觉您没有正确关联数据库列。在这种情况下,您需要创建迁移:
rails g migration AddForeignKeyToEventOptions
然后在迁移文件中,您需要为event_id添加一个字段:
...
def change
add_column :event_options, :event_id, :integer
end
...
然后您需要运行迁移:
rake db:migrate
一旦这些内容正确关联,您需要重新启动控制台,然后尝试将event_option与任何事件相关联:
EventOption.create(
description:"You give us money. We paint your face.",
price: 250.00,
name: "People Painting 1",
event: 1 # Supposing that event with id: 1 exists.
)
修改强> 这是指向创建迁移的rails文档的链接: http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-migration
我正在看这个部分:
class AddUserRefToProducts < ActiveRecord::Migration[5.0]
def change
add_reference :products, :user, foreign_key: true
end
end
答案 1 :(得分:0)
怎么样:
event = Event.create(name:"Face Painting", active:true)
EventOption.create(
description: "You give us money. We paint your face.",
price: 250.00,
name: "People Painting 1",
event: event
)
此外,除非您在一行中组合两个语句,否则Ruby中不需要分号。