2012-07-08 60 views
0

我想要的: 我可以上傳文件並將其分配給對象(例如Person)的站點。 對於上傳,我使用的是carrierwave。我想要有兩個分開的模型:「人物」和「附件」。每個人只有一個附件。 在我看來,我想設置上傳到一個嵌套的形式,'field_for'。未知的屬性_id與嵌套的模型和表格

我的代碼

#app/models/person.rb 
has_one :attachment 
accepts_nested_attributes_for :attachment 
attr_accessible :name, :attachment_attributes 

#app/models/attachment.rb 
attr_accessible :description, :file 
belongs_to :person 
mount_uploader :file, AttachmentUploader 

#app/controllers/person_controller.rb 
def new 
    @person = Person.new 
    @person.build_attachment 
end 

#app/views/person/new.html.haml 
= form_for @person, :html => {:multipart => true} do |f| 
    = f.fields_for :attachment do |attachment_form| 
    attachment_form.file_field :file 
    = f.submit 

我的問題: 當我試圖打開new.html我收到此錯誤: 未知屬性:PERSON_ID

我有不知道爲什麼會出現此錯誤。 有人有想法嗎?

(我用的導軌3.2.6與1.8.7紅寶石)

+0

附件表中是否有'person_id'列? – davidb 2012-07-09 14:12:33

+0

@davidb附件表中沒有'person_id'列。不應該'belongs_to:person'創造這個? – Sebastian 2012-07-11 12:08:14

回答

2

當建立兩個模型之間的關係總是有兩個步驟。

1.)創建需要的列/表。

當您有1..n或1..1的關係時,需要在其中一個表中有一個關聯列。這些列不是自動創建的。你需要創建它們。對於這個fiorst創建遷移:

rails g migration addColumnToTable 

這會在你需要編輯db/migrate/遷移文件。在up方法中添加add_colun命令添加一列

add_column :tablename, :column_name, :column_type 

你會發現整個文檔在這裏:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

然後,你需要通過執行rake db:migrate

2.運行遷移)添加(這是你已經做的!)

這應該爲你做,...

0

只需在您的附件表中添加一個person_id列即可。這是外鍵軌道正在尋找。