2

我被这个堆叠了好几天,尝试了一切。

我正在尝试做一个简单的有很多关联,但它拒绝工作:

我需要的是每个球体都有一个与之关联的 orb_type。

我生成脚手架:

rails generate scaffold orb_type nome
rails generate scaffold orb nome:string descr:text orb_type_id:integer

制作 rake db:migrate,

更改模型:

class Orb < ActiveRecord::Base
  has_many :orb_types
  validates_associated :orb_types
  attr_accessible :descr, :nome, :orb_type_id
  validates :nome, uniqueness: true, presence: true
end

class OrbType < ActiveRecord::Base
  attr_accessible :nome
  validates :nome, uniqueness: true, presence: true
  belongs_to :orb
end

然后试图让它工作:

$ rails c
1.9.3-p448 :001 > tipo = OrbType.new nome: "Planeta"
1.9.3-p448 :002 > tipo.save
1.9.3-p448 :003 > tipo = OrbType.find(1)
1.9.3-p448 :004 > planeta = Orb.new nome:"Testname", descr: "TestDescr"
1.9.3-p448 :005 > planeta.orb_type = tipo

在最后一行我得到错误:

NoMethodError: undefined method `each' for #<OrbType:0x00000003dc02a0>

这是怎么回事?下划线和rails“约定”让我头疼。

我看到了很多其他类似的主题,但他们的解决方案都没有奏效!

4

2 回答 2

3

你的协会是错误的方式。(你的脚手架很好,只需要左右切换belongs_tohas_many

像这样改变你的模型:

class Orb < ActiveRecord::Base
  belongs_to :orb_type
  validates_associated :orb_types
  attr_accessible :descr, :nome, :orb_type_id
  validates :nome, uniqueness: true, presence: true
end

class OrbType < ActiveRecord::Base
  has_many :orbs
  attr_accessible :nome
  validates :nome, uniqueness: true, presence: true
end

现在可以为一个球体赋予一个类型,并且可以为多个球体赋予一个类型。

于 2013-09-16T16:02:41.800 回答
2

orb_type_id在你的模型中有一个Orb是问题的一部分。你是说Orb有很多OrbTypes,但orb_type_id本质上只允许一个,而OrbType属于的,Orb这意味着OrbType需要orb_id.

假设多对多关系是您最可能需要关联模型的目标:

class Orb < ActiveRecord::Base
  has_many :orb_types, :through => :orb_associations
  has_many :orb_accociations
  validates_associated :orb_types
  attr_accessible :descr, :nome, :orb_type_id
  validates :nome, uniqueness: true, presence: true
end

class OrbAccociations < ActiveRecord::Base
  belongs_to :orb
  belongs_to :orb_type
end

class OrbType < ActiveRecord::Base
  attr_accessible :nome
  validates :nome, uniqueness: true, presence: true
  has_many :orb_associations
  has_many :orbs, :through => :orb_associations
end
于 2013-09-16T14:57:10.610 回答