我正在尝试使用角度发送json到rails后端提交投票。我正试图将投票与用户联系起来。当我使用json&提交投票时angular,新的投票被添加到数据库,但user_id为null。我尝试使用仅使用rails进行提交并且它有效(投票有user_id)
控制器
def yesvote
@question = Question.find(params[:id])
yesvote = Yesvote.create(yes: params[:yes], user: current_user, question: @question)
respond_to do |format|
format.html{
if yesvote.valid?
redirect_to :back
else
flash[:danger] = "once only!"
redirect_to :back
end
}
format.json{
if yesvote.save
render status: 200, json: yesvote
else
render status: 422, json: {
message: "failed.",
errors: yesvote.errors
}.to_json
end
}
end
end
角
$scope.voteYes = function (){
var parameter = JSON.stringify({ yes: true });
$http.post('/questions/' + $scope.number + '/yesvote.json', parameter)
.success(function (result) {
console.log(result);
})
.error(function (data, status) {
console.log(data);
});
}
yesvote model
class Yesvote < ActiveRecord::Base
belongs_to :user
belongs_to :question
validates_uniqueness_of :user, :allow_blank => true, scope: :question
end
sessions_helper current_user
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end