2014-09-03 3 views
0

서버에 레일을 사용하고 httppost 방법으로 데이터를 게시 한 다음 데이터를 데이터베이스에 저장합니다. 이를 위해 두 모델과 컨트롤러가 있습니다 : bolouk 및 'radif'.레일 연결 : 생성 작업의 저장 방법이 잘못되었습니다.

class Radif < ActiveRecord::Base 
    belongs_to :bolouk 
end 

내가 새 bolouk을 만들 수 있습니다,하지만 난 새로운 radif를 생성 할 때, 나는 필요한 모든 방법을 보내

models/bolouk.rb :

class Bolouk < ActiveRecord::Base 
    has_many :radifs, :dependent => :destroy 
end 

models/radif.rb 나는 관계 아래에 있습니다 데이터베이스에 새로운 radif (예 : bolouk_id 및 radif 매개 변수)를 작성하고이 데이터를 레일 서버 및 create action에 수신합니다. 그러나 새 메소드를 생성하려면 500 Internal Error.

controller/api/v1/radifs_controller.rb

는 :

class Api::V1::RadifsController < Api::V1::BaseController 
    def create 
    @radif = Radif.create(radif_params) 
    if @radif.valid? 
     puts "if" 
     respond_with @radif, :location => api_bolouk_radifs_path 
    else 
     puts "else" 
     respond_with @radif.errors, :location => api_bolouks_radifs_path 
    end 
    end 
    private 
    def radif_params 
    params.require(:radif).permit(:bolouk_id, :describe, :price) 
    end 
end 

는 내가 컨트롤러를 정의 @radifinvalid하고 데이터베이스에 @radif를 저장하지 않습니다 감지, 일부 로그의 조치를 작성했습니다. 나는 아래에서 서버 로그를 넣어 : newradif.html :

<form ng-submit="saveRadif()" class="form-horizontal" role="form"> 
        <div> 
         <ul> 
          <li ng-repeat="err in errors">{{err}}</li> 
         </ul> 
        </div> 
        <div class="form-group"> 
         <label for="radifdescribe" class="col-sm-2 control-label"><span>Describe:</span></label> 
         <div class="col-sm-4"> 
          <input ng-model='modalRadif.describe' class="form-control" id="radifdescribe" placeholder="describe"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label for="radifprice" class="col-sm-2 control-label"><span>Price</span></label> 
         <div class="col-sm-4"> 
          <input ng-model="modalRadif.price" class="form-control" id="radifprice" placeholder="price"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="col-sm-offset-2 col-sm-10"> 
          <button type="submit" class="btn btn-success">Create</button> 
         </div> 
        </div> 
       </form> 

및 AngularJS와 컨트롤러 :

Started POST "/api/bolouks/23/radifs?describe=110&price=128" for 127.0.0.1 at 2014-09-03 16:05:37 +0430 
Processing by Api::V1::RadifsController#create as JSON 
    Parameters: {"bolouk_id"=>"23", "describe"=>"110", "price"=>"128", "radif"=>{"bolouk_id"=>"23"}} 
    User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 7 ORDER BY "users"."id" ASC LIMIT 1 
    (0.0ms) begin transaction 
    (0.0ms) rollback transaction 
else 
Completed 500 Internal Server Error in 27ms (Views: 1.0ms | ActiveRecord: 1.0ms) 

내가 AngularJS와 데이터를 전송, 나는 코드 아래에있는

$scope.saveRadif = function(){ 
      Radifs.create($scope.modalRadif, {bolouk_id: $scope.saveBolouk.id}).$promise.then(function(data){ 
       $scope.radifs = Radifs.index({bolouk_id: $scope.saveBolouk.id}); 
    //   $scope.saveRadif = data; 
      }) 
       .catch(function (err) { 
        console.log(err.data); 

       }) 
     } 
app.factory('Radifs', function($resource) { 
    return $resource('/api/bolouks/:bolouk_id/radifs', {bolouk_id: '@bolouk_id'}, { 
     index: { method: 'GET', isArray: true}, 
     create: { method: 'POST' } 
    }); 
}); 

어떻게 할 수 이 문제를 해결 하시겠습니까?

+1

설명 및 가격은 매개 변수의 radif 해시 외부에 있습니다. 양식을 보여줄 수 있습니까? 또한 create 대신 save 메소드를 호출해야합니다. – Mandeep

+0

질문 양식을 추가합니다. – mgh

+0

@Mandeep 가이드가 매우 유용합니다. 양식을 확인하고 데이터 전송 유형을 편집합니다. – mgh

답변

0

모델 클래스에서 Bolouk 모델과 Radif 모델간에 has_many 및 belongs_to 연관을 정의했습니다. 따라서 다음과 같은 방법으로 Bolouk 객체에 속한 새로운 Radif 객체를 만들 수 있습니다.

def create 
    @bolouk = Bolouk.find(params[:bolouk_id]) 
    @radif = @bolouk.radifs.build(radif_params) 
    if @radif.save 
    respond_with @radif, :location => api_bolouk_radifs_path 
    else 
    respond_with @radif.errors, :location => api_bolouk_radifs_path 
    end  
end 
+0

이 코드를'radifs_controller'에 추가했지만, 데이터는 다시 데이터베이스에 저장되지 않습니다. – mgh

+0

로그인 컨트롤러를 추가했습니다.'@ radif'는 저장하지 않고'else' 문을 실행합니다. – mgh

+0

'@ radif.save'와'@ radif.save! '사이에는 어떤 차이점이 있습니까? '@ radif.save! '를 사용하면 다음과 같은 오류가 발생합니다 :''검증에 실패했습니다 : 설명은 비워 둘 수 없습니다. 가격은 비워 둘 수 없습니다' '. – mgh