簡體   English   中英

未定義的方法構建,在rails 3.2中構建has_many關聯

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM