Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

belongs_to returns nil when foreign key column doesnt exists: should at least warn

#6209

class SomeTable < ActiveRecord::Base
belongs_to :moo end

If you say SomeTable.first.moo you will get nil. SomeTable does not have a column called moo_id.

Shouldn't this at least throw a warning that the column moo_id does not exist? Maybe even throw some type of exception?

I also see that no sql is actually executed.. Does belongs to have a type of short circuit that first checks the attribute hash and returns nil if the attributes[:fk] returns nil? If that is the case, should it first check that the key is actually in the attributes hash?

Reported by Jake Dempsey · December 22nd, 2010 @ 05:15 PM

State: stale
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Alexander Zubkov
    Alexander Zubkov

    I believe Rails should not handle any case when a programmer makes an error and warn about it. Handling such cases yields additional code, growing in size and losing performance.

    About the fact SQL is not executed at all, it is up to Rails developers to answer.

    December 22nd, 2010 @ 09:03 PM

  2. Jake Dempsey
    Jake Dempsey

    While I can appreciate your comment and agree that overly defensive programming is usually not a good idea and can lead to bloat, I found it strange that I did not get any feedback as to why I was getting nil and no sql was being executed.

    I stumbled on this today because a dev was inquring about a relationship on a model we have. It had a belongs_to :obj relationship but no corresponding col. After digging, it was left over from some refactoring that was done.

    Wanted to at least capture it here for the Rails devs to decide on its fate.

    December 22nd, 2010 @ 09:36 PM

  3. rails
    rails
    • State changed from new to open

    This issue has been automatically marked as stale because it has not been commented on for at least three months.

    The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.

    Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.

    March 29th, 2011 @ 01:00 AM

  4. rails
    rails
    • State changed from open to stale

    March 29th, 2011 @ 01:00 AM