开发者

NoMethodError when using :include on association in Rails 3 with Active Record

开发者 https://www.devze.com 2023-04-05 02:26 出处:网络
Obviously I\'m missing something simple here. Here are my two classes and the code I\'m calling. When I use :include with find, it blows up and gives me a NoMethodError on the find line. When I don\'t

Obviously I'm missing something simple here. Here are my two classes and the code I'm calling. When I use :include with find, it blows up and gives me a NoMethodError on the find line. When I don't use :include it works just fine (but obviously doesn't do the join)

Called Code

def index
    @users = User.find(:all, :include => [:org])
end

Classes

class User < ActiveRecord::Base
    belongs_to :org, :primary_key => :org_id
end

class Org < ActiveRecord::Base
    #define primary key because it is not :id
    #because this table is in an old db 开发者_开发技巧
    #that can't be changed
    set_primary_key :org_id

    has_one :user

    def full_name
        "#{emp_fname} #{emp_lname}"
    end
end

The exact error

NoMethodError (You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each):


What version of rails are you on? Your tag says 3 - is it 3.1 or one of the 3.0.x series? Regardless, it seems in 3.0.x this :include hash syntax for find isn't supported.

Try User.includes(:org).find(:all).


Ok, so after a lot of digging and trial and error, basically it was a combination of having one table in one schema and the other in a different schema. By specifying the fully qualified table name for our active record objects, active record stopped throwing up on itself.

So the final code:

Called Code

def index
    @users = User.includes(:org)
end

Classes

class User < ActiveRecord::Base
    set_table_name "DOC_REQUEST.USERS"

    belongs_to :org, :primary_key => :org_id
end

class Org < ActiveRecord::Base
    set_table_name "AOS.ORG"

    #define primary key because it is not :id
    #because this table is in an old db 
    #that can't be changed
    set_primary_key :org_id

    has_one :user

    def full_name
        "#{emp_fname} #{emp_lname}"
    end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消