Ruby on Rails - 由于关联导致缺少属性错误
Ruby on Rails - Missing Attribute Error as a result of association
我有两个模型。
- 公司
- 备忘录
我希望公司有多个备忘录,而备忘录只有一个公司。
memorandum.rb
class Memorandum < ActiveRecord::Base
belongs_to :company
end
company.rb
class Company < ActiveRecord::Base
has_many :memorandums, dependent: :destroy
# validation lines omitted
end
当我尝试将外键分配给备忘录时,出现缺少属性错误 can't write unknown attribute "company_id"
我在companys controller里面分配公司。备忘录在此之前创建,当前备忘录的 ID 保存在会话哈希中。
companies_controller.rb
def create
@company = Company.new(company_params)
Memorandum.find(session[:memorandum_id]).company = @company
respond_to do |format|
if @company.save
format.html { redirect_to @company, notice: 'Company was successfully created.' }
format.json { render action: 'show', status: :created, location: @company }
else
format.html { render action: 'new' }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
end
我强烈建议您阅读 Rails 上的 Ruby Active Record Association. 指南,那里用示例非常清楚地解释了概念。
这里有两个示例链接:has_many and belongs_to 可以帮助您理解。
要解决您当前的问题,您需要迁移以将 company_id
添加到您的 memorandums
table:
rails g migration addCompanyIdToMemorandums company_id:integer
然后 运行 迁移:
bundle exec rake db:migrate
正如上面的指南所解释的,您需要在 belongs_to 关联的 table 中使用一个外键来指向它的父 table。因为,你的备忘录 belongs_to company
,所以你必须在你的备忘录 table 中添加 company_id
我们刚刚使用上述迁移所做的。
我有两个模型。
- 公司
- 备忘录
我希望公司有多个备忘录,而备忘录只有一个公司。
memorandum.rb
class Memorandum < ActiveRecord::Base
belongs_to :company
end
company.rb
class Company < ActiveRecord::Base
has_many :memorandums, dependent: :destroy
# validation lines omitted
end
当我尝试将外键分配给备忘录时,出现缺少属性错误 can't write unknown attribute "company_id"
我在companys controller里面分配公司。备忘录在此之前创建,当前备忘录的 ID 保存在会话哈希中。
companies_controller.rb
def create
@company = Company.new(company_params)
Memorandum.find(session[:memorandum_id]).company = @company
respond_to do |format|
if @company.save
format.html { redirect_to @company, notice: 'Company was successfully created.' }
format.json { render action: 'show', status: :created, location: @company }
else
format.html { render action: 'new' }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
end
我强烈建议您阅读 Rails 上的 Ruby Active Record Association. 指南,那里用示例非常清楚地解释了概念。
这里有两个示例链接:has_many and belongs_to 可以帮助您理解。
要解决您当前的问题,您需要迁移以将 company_id
添加到您的 memorandums
table:
rails g migration addCompanyIdToMemorandums company_id:integer
然后 运行 迁移:
bundle exec rake db:migrate
正如上面的指南所解释的,您需要在 belongs_to 关联的 table 中使用一个外键来指向它的父 table。因为,你的备忘录 belongs_to company
,所以你必须在你的备忘录 table 中添加 company_id
我们刚刚使用上述迁移所做的。