[英]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.