Problems with STI in has_many/belongs_to in Rails 1.1


#1

I have a problem that surfaced in my attempt to upgrade my application
to Rails 1.1.

We have a STI model on the “belongs_to” side of a has_many/belongs_to
relationship. All my unit tests for this model pass, and the
relationships all seem to work fine.

But in my functional tests, I’m getting errors. I’ve traced it back
into the call to the has_many association returning nil (To put it in
familiar terms, this is like author.posts returning nil). I was under
the impression that a call to something like author.posts would NEVER
return nil, you would just get an empty array. In either case, it’s
bad, because in my functional test, it should be getting at least one
“post” back.

Does anyone have any insight here? I’ve been banging my head against a
brick wall for a couple of days now, and I’m about ready to give up.


Lori O.
http://blog.dragonsharp.com


#2

On Monday, April 03, 2006, at 5:06 AM, Lori O. wrote:

the impression that a call to something like author.posts would NEVER
return nil, you would just get an empty array. In either case, it’s
bad, because in my functional test, it should be getting at least one
“post” back.

Ok, I’ve narrowed this down to a regression in eager loading behavior.

Let me reframe the example a little. Let’s say we have Author and Topic
and Post. Now, author has_many :topics, and topic has_many :posts. To
throw a wrench in the works, the Author also has a “current_topic” (So
they can logoff, and login, and start at the same place they left off),
represented by current_topic_id in the authors table.

In Rails 1.1, when I go after author.current_topic.posts, I get nil. In
Rails 1.0, this works fine.

class Author
has_many :topics
belongs_to :current_topic, :class_name => “Topic”, :foreign_key =>
“current_topic_id”
end

class Topic
has_many :posts
has_one :current_for_author, :class => “Author”, :foreign_key =>
“current_topic_id”
end

class Post
belongs_to :topic
end

I’ve tried using :include => :posts on the belongs_to :current_topic,
but that really doesn’t work (the generated SQL is bizarre). Any other
ideas are welcome.

Now that I understand it, I can work around it, but I think it qualifies
as a bug…


Lori O.
http://blog.dragonsharp.com


#3

On Monday, April 03, 2006, at 10:04 PM, Lori O. wrote:

Rails 1.0, this works fine.
“current_topic_id”
Now that I understand it, I can work around it, but I think it qualifies
as a bug…

I guess I should also point out that in my case “Post” is an STI class.


Lori O.
http://blog.dragonsharp.com