include方法中的Active Record(对象不支持#inspect)

时间:2013-10-30 12:11:47

标签: mysql sql ruby activerecord associations

这是我的MySQL数据库架构:

create table url (
  id int(11) primary key,
  url text,
  url_md5 char(32),
  urlpath text,
  cleanurl text,
  title text
);

create table record (
  id int(11) primary key,
  uid varchar(25),
  url text,
  url_md5 char(32)
);

create table user (
  uid varchar(25) primary key
);

这是一个遗留项目,所以在我使用主动recorad之前创建的模式。我的ruby代码就像这样:

class User < ActiveRecord::Base
  self.table_name = 'user'

  has_many :records, class_name: 'Record', 
           foreign_key: 'uid', primary_key: 'uid'

  def self.cached_count
    @cached_count ||= User.count
  end
end

class Record < ActiveRecord::Base
  self.table_name = 'record'

  has_one :urldetail, class_name: 'Url',
          foreign_key: 'url_md5', primary_key: 'url_md5',
          select: [:urlpath, :cleanurl]
end

class Url < ActiveRecord::Base
  self.table_name = 'url'

  belongs_to :record, class_name: 'Record',
             primary_key: 'url_md5', foreign_key: 'url_md5'
end

看起来有点复杂。 urlrecord表按url_md5创建关联,record表和user表按uid创建关联。它们不是主键。当我使用includes时,它会显示如下错误:

2.0.0-p247 :003 > u.records.includes(:urldetail)
D, [2013-10-30T20:08:33.207225 #47431] DEBUG -- :   Record Load (9.3ms)  SELECT `record`.* FROM `record` WHERE `record`.`uid` = '5669408714090543819'
D, [2013-10-30T20:08:33.303839 #47431] DEBUG -- :   Url Load (45.7ms)  SELECT urlpath, cleanurl FROM `url` WHERE `url`.`url_md5` IN ('2029708d8c99a3f781b6d695ddedf80c', '977434e3d3b080971d67b6a5c3850d57', '784820ccc528cc3a3cf2df3b677f8761', '14eea8c73d7dab59dbdd6f2d5c19eaed', 'dfb5ea7bbca8018d5bf7aedf4f03df1f', 'aad852910d0f6d1c96fa82e99399800d', '873a263e4bcd28f9e95e150a746c1188')
(Object doesn't support #inspect)
 =>  

我搜索了问题但什么也没得到。


更新

如果我写u.records.includes(:urldetail).to_a,结果将是:

    SELECT urlpath, cleanurl FROM `url` WHERE `url`.`url_md5` IN ('2029708d8c99a3f781b6d695ddedf80c', '977434e3d3b080971d67b6a5c3850d57', '784820ccc528cc3a3cf2df3b677f8761', '14eea8c73d7dab59dbdd6f2d5c19eaed', 'dfb5ea7bbca8018d5bf7aedf4f03df1f', 'aad852910d0f6d1c96fa82e99399800d', '873a263e4bcd28f9e95e150a746c1188')
ActiveModel::MissingAttributeError: missing attribute: url_md5

但我确实有专栏url_md5

0 个答案:

没有答案