ActiveRecord的和使用HAS_ONE和放大器;有很多 [英] ActiveRecord and use of has_one & has_many

查看:127
本文介绍了ActiveRecord的和使用HAS_ONE和放大器;有很多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的模型,其中项目有一个项目类型和,自然许多项目可以是这种类型的。

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

因此​​,一个项目 HAS_ONE:project_type (名为键入)和项目类型 的has_many:项目

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

在SQL似乎是假设有在 project_types 表中的 PROJECT_ID 字段但没有任何意义如果项目类型可与许多项目相关的。我怀疑我的问题是,是与我希望能够参照项目类型 project.type 没有 project.project_type ,但我不知道我怎么会解决这个问题。

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.

推荐答案

您需要使用belongs_to的,而不是HAS_ONE的项目模型。

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

您还需要添加一个project_type_id列到项目表。

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

这篇关于ActiveRecord的和使用HAS_ONE和放大器;有很多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆