Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有许多协会不';不向表中添加列_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 有许多协会不';不向表中添加列

Ruby on rails 有许多协会不';不向表中添加列,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两张桌子(表A和表B)。A有很多B 在Rails控制台上,这段代码的第二行不起作用: @a = TableA.new @a.TableBs 我得到这个错误:PG::UndefinedColumn:错误:。。。不存在 感谢您的帮助这是因为您没有正确设置表,并且您正在查询一个类 按如下方式设置您的关联: class TableA < ActiveRecord::Base has_many :table_bs, inverse_of: :table_a, dependent: :des

我有两张桌子(表A和表B)。A有很多B

在Rails控制台上,这段代码的第二行不起作用:

@a = TableA.new
@a.TableBs
我得到这个错误:PG::UndefinedColumn:错误:。。。不存在


感谢您的帮助

这是因为您没有正确设置表,并且您正在查询一个类

按如下方式设置您的关联:

class TableA < ActiveRecord::Base
  has_many :table_bs, inverse_of: :table_a, dependent: :destroy
end

class TableB < ActiveRecord::Base
  belongs_to :table_a, inverse_of: :table_bs
end
更新

这里有一个关于和dependent::destroy的inverse\u的简短解释

inverse\u的
使关联对象在Rails中的查找性能更高。如果不将其添加到关联中,那么关联的Rails对象就不会指向相同的内存对象。这意味着如果没有的反向,您总是要点击数据库,以便Rails获取关联。但是,如果包含它,如果对象已经在内存中,Rails将只抓取该对象!它本质上是内存中的双向绑定


dependent::destroy
用于父对象,以确保在销毁父对象时销毁关联对象

请显示
表A
表B
的型号代码。另外,请注意,
TableBs
不是
TableA
的属性或方法,如果
table\u a
有很多:table\u bs
。您需要阅读有关的Rails文档。请尝试
@a.table\u bs
。没有任何rails关联宏(有一个、有多个等)将列添加到数据库中。您需要通过创建迁移并运行
rakedb:migrate
来添加它们。你能解释一下倒数和相依是什么意思吗?
@a = TableA.new

@b = TableB.new
@b.table_a = @a
@b.save

@a.table_bs
=> #<ActiveRecord::Associations::CollectionProxy [#<TableB id: 1, name: "Foo"]>