2017-05-26 8 views
0

私は管理者が新しい会社を作ることを許可したいという単純なアプリを持っています。Railsのクラスのための未定義のメソッド `build_for`

def create 
    @company = Company.find_by({ name: company_create_params[:company_name] }) 

    if @company.nil? 
     @company = Company.build_for(company_create_params) 
    else 
     return render :status => 200, :json => { 
       :error => true, 
       :reason => 'This company already exists in the database!' 
     } 
    end 

    if @company.save 
     return render :status => 200, :json => { 
       :success => true 
     } 
    else 
     return render :status => 500, :json => { 
       :error => true, 
       :reason => 'There was a problem adding the company' 
     } 
    end 
end 

private 

def company_create_params 
    params.require(:company).permit(:company_name, :company_total_credits) 
end 

をそして、私の会社のモデルは次のとおりです:次のようにコントローラでの私の作成方法がある

class Company < ActiveRecord::Base 
    has_many :role 
end 

しかし、私はAPIのポストを作るたびに、それは私にfor class #<....>

build_forエラーUndefined methodを与えますhas_manyの関係のためですか?役割の価値を追加したくないのですが、後でその役割を果たせるようにしたいのです。これを修正する方法はありませんか?

+0

あなたはバージョンをRailsの全体のエラー?を追加することはできますか? –

+0

'Company.build(...)'ではありませんか? – Gerry

+0

@Gerryはいそうです。それは私の悪かった、申し訳ありません! – anonn023432

答えて

3

ActiveRecordはbuild_forメソッドを提供しないため、エラーが発生します。

おそらくbuildを意味していました。これは、コレクションの関連付けで定義されたメソッドです。この場合、Companyはモデルではありませんので、newまたはcreateが必要です。

あなたの全体の動作が途中で、いくつかの規則に従うことによって大幅に減少させることができます

class Company < ActiveRecord::Base 
    has_many :roles 
    validates :company_name, uniqueness: true 
end 

# controller 
def create 
    @company = Company.new(company_create_params) 

    if @company.save 
    render json: { success: true } 
    else 
    render status: 500, json: { 
     error: true, 
     reason: @company.errors.full_messages.to_sentence 
    } 
    end 
end 
関連する問題