Note that there are some explanatory texts on larger screens.

plurals
  1. POActiveRecord and use of has_one & has_many
    primarykey
    data
    text
    <p>Consider this simple model, where a <code>Project</code> has one <code>ProjectType</code> and, naturally many <code>Projects</code> can be of that type.</p> <p>So a <code>Project</code> <code>has_one :project_type</code> (called <code>type</code>) and a <code>ProjectType</code> <code>has_many :projects</code>.</p> <p>In my migration I put (simplified for this example)</p> <pre><code>create_table :projects do |t| t.string :name, :null =&gt; false t.integer :type end create_table :project_types do |t| t.string :name, :null =&gt; false end </code></pre> <p>My Project class looks like this (again simplified for this example)</p> <pre><code>#!usr/bin/ruby require 'active_record' class Project &lt; ActiveRecord::Base has_one :type, :class_name =&gt; 'ProjectType' end </code></pre> <p>And my ProjectType looks like</p> <pre><code>#!usr/bin/ruby require 'active_record' class ProjectType &lt; ActiveRecord::Base has_many :projects end </code></pre> <p>I've written a simple Unit Test to check this works</p> <pre><code>#test creation of Projects and related objects. def test_projects_and_etc pt = ProjectType.create(:name =&gt; 'Test PT') project = Project.create(:name =&gt; 'Test Project', :type =&gt; pt) assert project.type.name == 'Test PT', "Wrong Project Type Name, expected 'Test PT' but got '#{project.type.name}'." # clean up project.destroy pt.destroy end </code></pre> <p>This test throws an error at the assert, saying</p> <pre><code>ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: project_types.project_id: SELECT "project_types".* FROM "project_types" WHERE ("project_types".project_id = 1) LIMIT 1 </code></pre> <p>The SQL seems to be assuming that there is a <code>project_id</code> field in the <code>project_types</code> table but that makes no sense if a <code>ProjectType</code> can be associated with many <code>Projects</code>. I suspect that my problem is something to do with my wanting to be able to refer to the <code>ProjectType</code> as <code>project.type</code> not <code>project.project_type</code>, but I am not sure how I'd fix this.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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