通过Restangular更新Rails模型(即JSON)

时间:2016-01-28 15:39:50

标签: javascript ruby-on-rails angularjs json

我需要知道很多Rails的人,AngularJS和Restangular,我尝试通过AngularJS从Rails更新模型,但是我对正在发送的参数感到复杂......

我在AngularJS控制器中使用此函数首先捕获表单中的数据(分配给poll_updated变量的数据),然后将更新请求发送到Rails ...

  $scope.editPoll = function() {   
    var poll_updated = {title: $scope.title, description: $scope.description, allow_anonymous_answer: $scope.allow_anonymous_answer, initial_message: $scope.initial_message, final_message: $scope.final_message};

    console.log(poll_updated);

    Restangular.one('polls', poll.id).put(poll_updated).then(function(poll_updated) {
      $state.go('add_data_poll', poll_updated);
    });
  };

请注意,poll.id是将要修改的民意调查的ID,并且我通过控制台打印poll_updated(据称是新数据)。

这是我在谷歌Chrome控制台中获得的......

Google Chrome's console

这是绝对正确的,那些是我发送的参数......

现在我向您展示Rails的日志

Rails console

在第一个矩形中,我们仍然可以看到发送的参数仍然是正确的(我可以说id也是正确的),但问题出在第二个矩形...这里我显示参数poll_params用于更新模型,并且它包含ID ...

这是来自Rails的polls_controller中的更新操作的代码...

def update
  puts "<(PARAMETERS)>: " + poll_params.to_s
  respond_to do |format|
    if @poll.update(poll_params)
      format.html { redirect_to @poll, notice: 'Poll was successfully updated.' }
      format.json { render :show, status: :ok, location: @poll }
    else
      format.html { render :edit }
      format.json { render json: @poll.errors, status: :unprocessable_entity }
    end
  end
end

我已经完成了多项测试,我得出的唯一结论是唯一的问题是poll_params没有获得我发送的所有参数,只有id

我该如何解决这个问题?

这些是我允许更新的参数......

def poll_params
  params.require(:poll).permit(:user, :title, :description, :allow_anonymous_answer, :initial_message, :final_message)
end

那么问题是什么呢?

1 个答案:

答案 0 :(得分:0)

这是正确的行为。您的params哈希看起来像这样:

{
  "allow_anonymous_answer" => false,
  "description" => "AAA",
  "final_message" => "AAA",
  "initial_message" => "AAA",
  "title" => "Poll B",
  "poll" => {
    "id" => 137
  }
}

但是poll_params哈希只包含一对,因为您只从poll哈希中提取params的值。

{
  "id" => 137
}

require仅返回具有指定键(:poll)的值。 http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require

因此,您的poll_params方法应如下所示:

def poll_params
  params.permit(:user, :title, :description, :allow_anonymous_answer, :initial_message, :final_message).except(:poll)
end

另一种解决方案是配置Restangular以发送嵌套在poll参数中的所有属性。