[英]Undefined method build, build has_many association in rails 3.2
我有以下問題:我必須在數據庫中創建一個新的關聯行。 我有:
companies table
references table
公司has_many
參考。
參考belongs_to
公司。
在我的公司表中,我具有以下屬性:
id | city | email | ...|
在我的參考表中,我具有以下屬性:
id | name | surname | company_id | ...|
Company.rb模型:
belongs_to :references
Reference.rb模型:
has_many :companies
在公司控制器中:
def create
@company = Company.new(company_params)
@company.references.build(params[:company][:email_r])
respond_to do |format|
if @company.save
format.html { redirect_to companies_index_path, :notice => 'created'}
format.json { render :json => companies_index_path, :status => :created, :location => @company }
else
format.html { render :action => "new" }
format.json { render :json => @company.errors, :status => :unprocessable_entity }
end
end
end
我的錯誤是:
undefined method `build' for nil:NilClass
根據您的表模式,關聯應該像company has many references
並且reference belong to a company
。 在Company.rb
,應如下所示-
class Company
has_many :references
end
在Reference.rb
它應該像
class Reference
belongs_to :company
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.