ActiveRecord::HasManyThroughCantAssociateNewRecords (Cannot associate new records through 'Page#imageables' on '#'. Both records must have an id in order to create the has_many :through record associating them.)

0 views
Skip to first unread message

Lucas

unread,
Apr 21, 2008, 12:08:35 AM4/21/08
to resource_controller
Hi,

I'm trying to setup a model relationship like this:

I have an Image model where I can associate it with any other model
(like Pages or Articles) using a polymorphic relationship with a join
table, so I can have more than one resource using the same image.

Here is my models:

class Image < ActiveRecord::Base
has_many :imageables
has_many :resources, :through => :imageables
end

class Imageable < ActiveRecord::Base
belongs_to :image
belongs_to :resource, :polymorphic => true
end

class Page < ActiveRecord::Base
has_many :imageables, :as => :resource, :dependent
=> :destroy, :include => :image
has_many :images, :through => :imageables
end


My ImagesController:

class ImagesController < ApplicationController
resource_controller
belongs_to :page
end


The problem is, when I access http://localhost:3000/pages/1/images/new
I get the following error:

Cannot associate new records through 'Page#imageables' on '#'. Both
records must have an id in order to create the has_many :through
record associating them.

Is there a way to make it work?

Thanks.

Bartek

unread,
Apr 23, 2008, 6:34:43 PM4/23/08
to resource_controller
Try adding the following code to your ImagesController and see if it
helps:

create.after do
@page.images << @image if parent_type == :page
end

private

def build_object
@object ||= Image.new
end

Bartek

Bartek

unread,
Apr 23, 2008, 6:41:25 PM4/23/08
to resource_controller
I forgot about "object_params", here is the correction:

  create.after do
    @page.images << @image if parent_type == :page
  end

  private

  def build_object
    @object ||= Image.new object_params
  end

Sean Schofield

unread,
May 14, 2008, 5:10:26 PM5/14/08
to resource_controller
FYI. I was running into the same problem using has_many_polymorphs
and this solution also worked for me as well.

Sean
Reply all
Reply to author
Forward
0 new messages