[英]Rails belongs_to relationship not working
目前,我的页面模型和公司模型之间的belongs_to关系存在问题。
当我在页面show.erb.html上并且访问@ page.company.id时,我收到以下错误消息:nil:NilClass的未定义方法'id'
在公司模型中带有和不带有attr_accessor方法的此错误消息。
页面模型:
class Page < ActiveRecord::Base
belongs_to :company
end
公司型号:
class Company < ActiveRecord::Base
attr_accessor :id, :name
has_many :pages
end
公司迁移:
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :name
t.timestamps
end
end
end
页面迁移:
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :name
t.references :companies, index: true
t.timestamps
end
end
end
由于页面只有一家公司,因此页面迁移应使用:
t.references :company, index: true
(单数),而不是:companies(复数)。 这应该允许导轨正确地填充它。
协会
由于Rails旨在在关系数据库堆栈上运行,因此您必须了解此结构在定义和创建模型中的ActiveRecord关联中所扮演的角色。
为了给您一些想法-ActiveRecord实际上是一个称为“ ORM”(对象关系映射器)的东西 -这意味着它将管理您应用程序中“对象”之间的关系 。 由于Rails通过基于Ruby构建,因此是面向对象的 ,因此ActiveRecord在管理对象之间的关系方面起着不可或缺的作用
您要指的问题是如何正确构建这些关系:
楷模
您的问题的答案是:
#app/models/page.rb
Class Page < ActiveRecord::Base
#fields id | company_id | other | attributes | created_at | updated_at
belongs_to :company
end
#app/models/company.rb
Class Company < ActiveRecord::Base
#fields id | title | other | page | attributes | created_at | updated_at
has_many :pages
end
为了演示表格的外观,可以使用以下Rails文档 :
这意味着,参考您的问题,您可以使用Martin
的答案,也可以手动添加company_id
列(我们可以这样做):
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :name
t.string :company_id
t.timestamps
end
end
end
数据表
您应该知道的其他一些信息:
foreign_keys
建立关联-每当在模型中创建“ relationship”时,它都会触发ActiveRecord来识别关联的foreign_key
: primary key
确定。 每次在Rails中加载对象时,它实际上是在数据库中寻找它具有的对应id
这意味着,如果您希望在Rails中标识记录,则需要确保它们在数据库中具有primary key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.