【发布时间】:2017-04-21 16:38:38
【问题描述】:
我有以下型号
- 地址
- 汽车
- 用户
我在模型之间有以下关系。
- 每辆车都有一个地址(一对一关系)
- 每个用户都有一个地址(一对一关系)
地址模型
class Address < ApplicationRecord
belongs_to :car
belongs_to :user
end
汽车模型
class Car < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
用户模型
class User < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
数据库表
- 汽车有一列 address_id 作为外键
- 用户有一个列 address_id 作为外键
迁移 用户
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :username
...
t.references :Address, foreign_key: true
end
end
end
汽车迁移
class CreateCars < ActiveRecord::Migration[5.0]
def change
create_table :cars do |t|
t.string :chasis
...
t.references :Address, foreign_key: true
end
end
end
现在,当我尝试从 User/new.html.erb 创建嵌套表单时,出现以下错误。
user_id 是 Address 中的未知属性。
用户控制器.rb
class UsersController < ApplicationController
def new
@user = User.new
@user.build_address
end
...
end
我的嵌套表单没有被渲染。
嵌套形式
<%= form_for @user, html: { class: 'form-horizontal' } do |f|%>
<%= f.fields_for :address do |fact| %>
<div class="field form-group">
<%= f.label :add1, class: 'col-sm-2 control-label' %>
<div class="col-sm-10">
<%= f.text_field :add1, class: 'form-control' %>
</div>
</div>
<div class="field form-group">
<%= f.label :add2, class: 'col-sm-2 control-label' %>
<div class="col-sm-10">
<%= f.text_field :add2, class: 'form-control' %>
</div>
</div>
<% end %>
<div class="field form-group">
<div class="col-sm-offset-2 col-sm-2">
<%= f.submit class: 'form-control btn btn-primary' %>
</div>
</div>
<% end %>
我怀疑我的迁移文件中存在一些问题。但是数据库表是以我想要的方式创建的。
【问题讨论】:
-
请发布
CreateAddresses迁移。 -
我认为你在地址迁移中没有user_id。
标签: ruby-on-rails ruby nested-forms