This project is archived and is in readonly mode.

#5605 ✓committed
Erik Fonselius

Using Model.includes(:relation_with_custom_primary_key)

Reported by Erik Fonselius | September 10th, 2010 @ 12:58 PM | in 3.x

Hi

It seems that when specifying a custom primary key in a belongs_to
belongs_to :model, :primary_key => :some_key
and then calling

Model.includes(:other_model).all

will throw a exception.
This is still a working theory but I created a sample app to demonstrate.
I tried adding a test in rails/activerecord/cases/associations_test.rb

def test_eager_loading_with_custom_primary_key
    assert_nothing_raised{Firm.includes(:account).all} 
end

But for some reason this passes when I run the test.

Which led me to create a example app where i tried

belongs_to :post, :primary_key => :id

that also throws the same exception

http://github.com/Fonsan/custom_primary_key_preload created by the following sequence

rails new custom_primary_key_preload
cd custom_primary_key_preload
rails g scaffold Post content:string
rails g scaffold Comment post_id:integer content:string
rake db:migrate

# db/seeds.rb
@post = Post.create(:content => "test")
Comment.create(:content => "test comment", :post_id => @post.id)

rake db:seed

# app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :post, :primary_key => :id
end

# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
# GET /comments
# GET /comments.xml
def index
  @comments = Comment.includes(:post)

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @comments }
  end
end

...
end

rails s

Visit /comments

NoMethodError in Comments#index

Showing /home/fonsan/custom_primary_key_preload/app/views/comments/index.html.erb where line #12 raised:

undefined method type' for nil:NilClass

Extracted source (around line #12):

9:


10:
11:
12: <% @comments.each do |comment| %>
13:
14:
15:
<%= comment.post_id %> <%= comment.content %>

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages