Forum: Ruby on Rails Odd issue relating to polymorphic associations and find_or_c

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
2f9a03aa0fcfe945229cb6126eda2cb2?d=identicon&s=25 Philip Hallstrom (Guest)
on 2007-01-19 16:30
(Received via mailing list)
Hi -

I have a GalleryEntry model.  I also have a View model.

   GalleryEntry has_many :views, :as => :viewable
   View belongs_to :viewable, :polymorphic => true

My View schema looks like this:

   create_table :views do |t|
     t.column :views, :integer, :default => 0
     t.column :viewed_on, :date
     t.column :viewable_id, :integer
     t.column :viewable_type, :string, :limit => 45

If I do this via console:


the following SQL shows up in my logs (formatted for readability):

   GalleryEntry Load (0.000656)   SELECT * FROM gallery_entries LIMIT 1

   ImageGalleryEntry Columns (0.011212)   SHOW FIELDS FROM

   View Columns (0.002493)   SHOW FIELDS FROM views

   View Load (0.001140)   SELECT * FROM views
                 WHERE (views.viewable_id = 14265
                        views.viewable_type = 'GalleryEntry'
                 AND (views.`viewed_on` = '2007-01-12' )
                 LIMIT 1

   SQL (0.000084)   BEGIN

   SQL (0.000265)   INSERT INTO views
                    (`viewed_on`, `views`, `viewable_type`,
                    ('2007-01-12', 0, NULL, 14265)

   SQL (0.000068)   COMMIT

What I don't understand is why during the "find" part of find_or_create
does it knows to set viewable_type = 'GalleryEntry', but then once it
doesn't find it and goes to create it, it doesn't set it correctly, but
instead uses NULL?

Is this a bug?  Perhaps fixed in 1.2?  My rails environment:

About your application's environment
Ruby version                 1.8.5 (i686-darwin8.8.2)
RubyGems version             0.9.0
Rails version                1.1.6
Active Record version        1.14.4
Action Pack version          1.12.5
Action Web Service version   1.1.6
Action Mailer version        1.2.5
Active Support version       1.3.1
Application root             xxxxxxxx
Environment                  development
Database adapter             mysql
Database schema version      171

Any and all insights are greatly appreciated! Thanks!

This topic is locked and can not be replied to.