Trouble with has_one

Hi,

I’m trying to write a blog application where each post has a single
header image associated.

My models:

class Post < ActiveRecord::Base
belongs_to :blog
has_many :images
has_one :header
end

class Header < ActiveRecord::Base
file_column :image_path
end

class Image < ActiveRecord::Base
belongs_to :post
file_column :image_path
end

The controller targets I have used:

def uploadImage
Post.find(params[:id]).images.create(params[:image])
@post = Post.find(params[:id])
flash[:notice] = “Image was successfully uploaded”
redirect_to :action => ‘showBlogPosts’, :id => @post.blog_id
end

def uploadHeaderImage
Post.find(params[:id]).header.create(params[:header])
@post = Post.find(params[:id])
flash[:notice] = “Image was successfully uploaded”
redirect_to :action => ‘showBlogPosts’, :id => @post.blog_id
end

As you can see POST has two children, image and header.

POST (has_many) images
POST (has_one) header

When I try to create a header for a post, I get:
You have a nil object when you didn’t expect it!
You might have expected an instance of ActiveRecord::Base.
The error occured while evaluating nil.create

From development log I could see that the SQLs built in case of has_many
and has_one differ. has_one has LIMIT 1 attached.

Is that the reason why this is failing? How to get around this?

On 7/17/06, Nishant K. [email protected] wrote:

def uploadHeaderImage
Post.find(params[:id]).header.create(params[:header])

You probably don’t really have a header at this point, so it will be
nil. You should create a new Header and then assign it to the Post
instance that you get back from find().

– James

“Nishant K.” [email protected] wrote
in message news:[email protected]

Hi,

I’m trying to write a blog application where each post has a single
header image associated.

snip

The error occured while evaluating nil.create
the create syntax for has_one associations is a little different to
has_many. Try this instead:
Post.find(params[:id]).create_header(params[:header])

You can also do something like:

h = Header.create(params[:header])
p = Post.find(params[:id])
p.header = h

hth