# Odd issue relating to polymorphic associations and find\_or\_c

**URL:** <https://www.ruby-forum.com/t/odd-issue-relating-to-polymorphic-associations-and-find-or-c/82405>\
**Category:** Rails\
**Created:** [January 19, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/odd-issue-relating-to-polymorphic-associations-and-find-or-c/82405 "2007-01-19T16:30:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phallstrom](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/f475e1/32.png) [@phallstrom](https://www.ruby-forum.com/u/phallstrom)\
**Post date:** [January 19, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/odd-issue-relating-to-polymorphic-associations-and-find-or-c/82405/1 "2007-01-19T16:30:10Z")

</div>

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  
end

If I do this via console:

GalleryEntry.find(:first).views.find\_or\_create\_by\_viewed\_on(Date.today)

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  
gallery\_entries

View Columns (0.002493) SHOW FIELDS FROM views

View Load (0.001140) SELECT \* FROM views  
WHERE (views.viewable\_id = 14265  
AND  
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`,  
`viewable_id`)  
VALUES  
(‘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!

-philip
