Polymorphic Associations

Hi,
I’m following the Polymorphic Associations test, issue as following.


class Product < ActiveRecord::Base
has_many :images, :as=>:imageable
end

class User < ActiveRecord::Base
has_many :images, :as=>:imageable
end

class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end

**migration:

class CreateImages < ActiveRecord::Migration
def self.up
create_table :images do |t|
t.integer :imageable_id
t.string :imageable_type
t.string :name

  t.timestamps
end

end

def self.down
drop_table :images
end
end

**rending views/images/show.html.erb

OwnerName: <%= @image.imageable%>

***** when i rendering the http://localhost:3000/images/1, the wrong message as following: ***** NameError in Images#show

Showing /home/orient/rails-app/temp1/app/views/images/show.html.erb
where line #20 raised:

wrong constant name user
Extracted source (around line #20):

17:
18:


19: OwnerName:
20: <%= @image.imageable%>
21:
22:


23:

Any one could help , thanks in advance!!

On Sep 24, 10:47Â pm, Orient F. [email protected] wrote:


I think @image.imageable returns an ActiveRecord Object, which you
can’t just display. If you are just testing:

@image.imageable.inspect should dump the active record object the
image is related to.

If you are trying to get an attribute of the imageable relation, since
there can be different relations you have to use the imageable_type to
make sure it is there and use something like @image.imageble.name

But does the image an imageable? how are you saving the image?

On Sep 27, 10:41 am, radhames brito [email protected] wrote:

But does the image an imageable? how are you saving the image?

I was just talking about polymorphic in general. For images I’d use
something like paperclip.

http://github.com/thoughtbot/paperclip

Then you’d have something like

class Image < ActiveRecord::Base
include Paperclip
belongs_to :imageable, :polymorphic => true
has_attached_file :photo,
:styles => {
:thumb=> “100x100”,
:small => “200x200>”,
:medium => “300x300>”,
:large => “400x400>” }

end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs