开发者

ActiveRecord and use of has_one & has_many

Consider this simple model, where a Project has one ProjectType and, naturally many Projects can be of that type.

So a Project has_one :project_type (called type) and a ProjectType has_many :projects.

In my migration I put (simplified for this example)

create_table :projects do |t|
  t.string :name, :null => false
  t.integer :type
end

create_table :project_types do |t|
  t.string :name, :null => false
end

My Project class looks like this (again simplified for this example)

#!usr/bin/ruby
require 'active_record'

class Project < ActiveRecord::Base
  has_one :type, :class_name => 'ProjectType'
end

And my ProjectType looks like

#!usr/bin/ruby
require 'active_record开发者_运维百科'

class ProjectType < ActiveRecord::Base
  has_many :projects
end

I've written a simple Unit Test to check this works

#test creation of Projects and related objects.
def test_projects_and_etc  
  pt = ProjectType.create(:name => 'Test PT')
  project = Project.create(:name => 'Test Project', :type => 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

This test throws an error at the assert, saying

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

The SQL seems to be assuming that there is a project_id field in the project_types table but that makes no sense if a ProjectType can be associated with many Projects. I suspect that my problem is something to do with my wanting to be able to refer to the ProjectType as project.type not project.project_type, but I am not sure how I'd fix this.


You need to use belongs_to instead of has_one on the project model.

You also need to add a project_type_id column on to the projects table.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜