【问题标题】:Undefined method build, build has_many association in rails 3.2未定义的方法构建,在rails 3.2中构建has_many关联
【发布时间】:2015-08-21 14:40:53
【问题描述】:

我有以下问题: 我必须在我的数据库中创建一个新的关联行。 我有:

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

【问题讨论】:

    标签: ruby-on-rails build ruby-on-rails-3.2 associations has-many


    【解决方案1】:

    根据您的表架构,关联应该类似于 - company has many referencesreference belong to a company。在Company.rb 中应该如下所示 -

    class Company
      has_many :references
    end 
    

    Reference.rb 中应该是这样的

    class Reference 
       belongs_to :company
    end
    

    【讨论】:

    • 是的,我把事情颠倒了……我真的很抱歉。现在它起作用了。我的代码中还有另一个错误。这个@company.references.build(params[:company][:email_r]) 应该是:@company.references.create(:email_r => params[:company][:email_r])。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多