Note that there are some explanatory texts on larger screens.

plurals
  1. PORails ActiveRecord: legacy table without primary key shows nil for result?
    text
    copied!<p>I've got a Rails app that'll be sitting on top of a legacy database with some ugly tables that I'm having to deal with. One is a <code>feature_attributes</code> table related to <code>features</code>. Problem is that this <code>feature_attributes</code> table doesn't have a primary key. I wouldn't think that'd be a problem, but evidently it is. I've got my model name which is different from the table name, but I'm using <code>set_table_name</code> to specify the right one.</p> <pre><code>class Feature &lt; ActiveRecord::Base has_many :feature_attributes end class FeatureAttribute &lt; ActiveRecord::Base set_table_name 'feature_attribute' belongs_to :feature end </code></pre> <p>Once I load a feature that I know has related <code>feature_attributes</code> and call <code>feature.feature_attributes</code> on it, I get <code>nil</code>. Matter of fact, even <code>FeatureAttribute.first</code> gives me <code>nil</code>. The result of <code>FeatureAttribute.any?</code> returns <code>false</code>. I'm worried that ActiveRecord isn't reading any of the data from the table because there isn't a primary key. Is that what's going on here?</p> <p>The <code>feature_attribute</code> table has the following columns.</p> <pre><code>feature_id attribute_name attribute_value created_date modified_date </code></pre> <p>Help!</p> <p><em>I'll also note that running the generated SQL directly against the MySQL server actually gets me the rows I want.</em></p> <pre><code>SELECT `feature_attribute`.* FROM `feature_attribute` WHERE `feature_attribute`.`feature_id` = 24; </code></pre> <p><strong>EDIT</strong>: I am so sorry. Next time I'll learn to check my <code>database.yml</code>. Evidently I was reading from a test database that had an identical feature table, but the <code>feature_attribute</code> table was totally empty.</p> <p>I feel like a moron. Thanks for your help, everyone; I'm up voting you all for your troubles. I did like just about everybody's answer. (Can I down vote myself? :))</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload