What I want:
A site where I can upload a file and assign it to an object (e.g. Person).
For the upload I am using carrierwave. I want to have two separated models: “Person” and “Attachment”. Every person has only one attachment.
In my view I would like to set the upload into a nested form, with ‘field_for’.
My Code:
#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
My problem:
When I am trying to open new.html I am getting this error:
unknown attribute: person_id
I have no idea why this error occurs.
Somebody an idea?
(I am using rails 3.2.6 with ruby 1.8.7)
When creating the association between two models there are always two steps.
1.) Creating the cholumns / table needed.
When you have a 1..n or 1..1 relation there needs to be a column for association in one of the tables. This columns arent created automaticly. You need to create them. For this fiorst create a migration:
This creates a migration file in
db/migrate/that you need to edit. In theupmethod add theadd_coluncommand to add a columnYou will find the whole documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
Then you need to run the migration by executing
rake db:migrate2.) Add the association to the models (This is what you have already done!)
That should do it for you,…