ruby-on-rails – Rails ActiveRecord:没有主键的遗留表显示结
我有一个Rails应用程序,它将位于遗留数据库之上,其中包含一些我不得不处理的丑陋表格.一个是与功能相关的feature_attributes表.问题是此feature_attributes表没有主键.我不认为这是一个问题,但显然是.我的模型名称与表名不同,但我使用set_table_name来指定正确的名称.
class Feature < ActiveRecord::Base has_many :feature_attributes end class FeatureAttribute < ActiveRecord::Base set_table_name 'feature_attribute' belongs_to :feature end 一旦我加载了一个我知道具有相关feature_attributes的功能并在其上调用feature.feature_attributes,我就会得到nil.事实上,甚至FeatureAttribute.first都给我零. FeatureAttribute.any的结果?返回false.我担心ActiveRecord没有读取表中的任何数据,因为没有主键.那是怎么回事? feature_attribute表具有以下列. feature_id attribute_name attribute_value created_date modified_date 救命! 我还要注意,直接针对MySQL服务器运行生成的SQL实际上可以获得我想要的行. SELECT `feature_attribute`.* FROM `feature_attribute` WHERE `feature_attribute`.`feature_id` = 24; 编辑:我很抱歉.下次我将学习检查我的database.yml.显然我正在从具有相同功能表的测试数据库中读取,但feature_attribute表完全为空. 我觉得自己像个白痴.谢谢大家的帮助;我为你的麻烦投票给大家.我确实喜欢每个人的答案. (我可以自己投票吗?:)) 解决方法
尝试也设置主键:
class FeatureAttribute < ActiveRecord::Base set_table_name 'feature_attribute' set_primary_key 'feature_id' belongs_to :feature end UPDATE 我认为你的问题在于其他地方.我刚刚测试过,ActiveRecords可以在没有主键的情况下正常工作: 对于一个简单的表: class CreateThings < ActiveRecord::Migration def change create_table :things,:id => false do |t| t.string :name t.timestamps end end end 在控制台中: Loading development environment (Rails 3.1.1) irb(main):001:0> Thing.create(:name=>'A name for the thing') (0.1ms) BEGIN SQL (0.3ms) INSERT INTO `things` (`created_at`,`name`,`updated_at`) VALUES ('2011-11-02 16:33:48','A name for the thing','2011-11-02 16:33:48') (40.3ms) COMMIT => #<Thing name: "A name for the thing",created_at: "2011-11-02 16:33:48",updated_at: "2011-11-02 16:33:48"> irb(main):002:0> Thing.first Thing Load (0.7ms) SELECT `things`.* FROM `things` LIMIT 1 => #<Thing name: "A name for the thing",updated_at: "2011-11-02 16:33:48"> irb(main):003:0> 更新2 irb(main):003:0> Thing.create(:name=>'Another thing') (0.2ms) BEGIN SQL (0.4ms) INSERT INTO `things` (`created_at`,`updated_at`) VALUES ('2011-11-02 16:40:59','Another thing','2011-11-02 16:40:59') (35.4ms) COMMIT => #<Thing name: "Another thing",created_at: "2011-11-02 16:40:59",updated_at: "2011-11-02 16:40:59"> irb(main):004:0> Thing.first Thing Load (0.5ms) SELECT `things`.* FROM `things` LIMIT 1 => #<Thing name: "A name for the thing",updated_at: "2011-11-02 16:33:48"> irb(main):005:0> Thing.last Thing Load (11.8ms) SELECT `things`.* FROM `things` ORDER BY `things`.`` DESC LIMIT 1 Mysql2::Error: Unknown column 'things.' in 'order clause': SELECT `things`.* FROM `things` ORDER BY `things`.`` DESC LIMIT 1 ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'things.' in 'order clause': SELECT `things`.* FROM `things` ORDER BY `things`.`` DESC LIMIT 1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |