2017-04-21 96 views
0

我有以下型號has_one和rails中的遷移問題?

  • 地址
  • 用戶

而且我有以下型號之間的關係。

  • 每一輛汽車都有一個地址(一個 - 一個關係)
  • 每個用戶都有一個地址(一個 - 一個關係)

地址模型

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 

現在,當我嘗試從用戶/ new.html.erb嵌套形式我得到以下錯誤。

user_id是在地址不明屬性。

User_controller.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 %> 

我懷疑沒有在我的移民文件的一些問題。但是數據庫表格是以我想要的方式創建的。

+1

請張貼'CreateAddresses'遷移。 – mudasobwa

+0

我想你在地址遷移中沒有user_id。 –

回答

0

不太清楚,但是:

t.references :Address, foreign_key: true 

不應該

t.references :address, foreign_key: true 

通知:address

0

用戶ID小(一)不存在。

首先您必須保存用戶。你可以嘗試fact.addr而不是f.addr

你可以發佈完整的用戶控制器文件代碼嗎?

<%= form_for @person, url: {action: "create"} do |person_form| %> 
    <%= person_form.text_field :name %> 
    <%= fields_for @person.contact_detail do |contact_detail_form| %> 
    <%= contact_detail_form.text_field :phone_number %> 
    <% end %> 
<% end %> 


<form accept-charset="UTF-8" action="/people" class="new_person" id="new_person" method="post"> 
    <input id="person_name" name="person[name]" type="text" /> 
    <input id="contact_detail_phone_number" name="contact_detail[phone_number]" type="text" /> 
</form> 

如果保存@person它也會自動爲聯繫人保存數據。

請參閱此鏈接瞭解更多信息

http://guides.rubyonrails.org/form_helpers.html