Sebastian
Sebastian

Reputation: 3399

Unknown attribute _id with nested models and form

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)

Upvotes: 0

Views: 1621

Answers (2)

coderek
coderek

Reputation: 1870

simply add a person_id column to your attachment table. that is the foreign key rails is looking for.

Upvotes: 0

davidb
davidb

Reputation: 8954

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:

rails g migration addColumnToTable

This creates a migration file in db/migrate/ that you need to edit. In the up method add the add_colun command to add a column

add_column :tablename, :column_name, :column_type

You 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:migrate

2.) Add the association to the models (This is what you have already done!)

That should do it for you,...

Upvotes: 2

Related Questions