我想通过http
和post
方法使用rails for server和post数据,然后将数据保存到数据库。为此,我有2个模型和控制器:bolouk
和'radif'。 我有关联如下:Rails关联:在创建操作中保存方法的类型无效
models/bolouk.rb
:
class Bolouk < ActiveRecord::Base
has_many :radifs, :dependent => :destroy
end
models/radif.rb
:
class Radif < ActiveRecord::Base
belongs_to :bolouk
end
我可以创建新的bolouk
,但是当我想创造新的radif
,我送,我需要为所有的方法在数据库中创建新的radif(如bolouk_id
和radif参数),并且我在rails服务器和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
我把一些日志中创建行动,我定义控制器检测@radif
为invalid
,不保存@radif
数据库。我把服务器日志如下:
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数据,我有下面的代码: 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控制器:
$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' }
});
});
我怎样才能解决这个问题?
您的描述和价格超出了参数中的radif散列值。你可以展示你的表单吗?你也需要调用save方法而不是create方法。 – Mandeep 2014-09-03 11:55:50
我将表单添加到问题中。 – mgh 2014-09-03 12:03:33
@Mandeep你的指导是非常有用的。我检查表单并编辑数据发送的类型。 – mgh 2014-09-03 20:47:09