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?