【问题标题】:Rails 5 Api model not saving fieldsRails 5 Api模型不保存字段
【发布时间】:2018-12-17 15:01:12
【问题描述】:

我有一个当前创建和验证用户的 rails 5.2 API(在 Postman 中测试)。但是,我添加了另一个名为 Stories 的模型,当我尝试创建新 Story 时,会创建一个故事,但只保存 id 属性。

这是我的 StoriesController:

class StoriesController < ApplicationController
  before_action :set_story, only: [:show, :update, :destroy]

  # GET /stories
  def index
    @stories = Story.all
    render json: @stories
  end

  # POST /stories
  def create
    @story = Story.new(story_params)
    if @story.save
      render json: @story, status: :created
    else
      render json: { errors: @story.errors.full_messages },
             status: :unprocessable_entity
    end
  end

  # GET /stories/:id
  def show
    render json: @story
  end

  # PUT /stories/:id
  def update
    @story.update(story_params)
    head :no_content
  end

  # DELETE /stories/:id
  def destroy
    @story.destroy
    head :no_content
  end

  private

  def story_params
    # whitelist params
    params.permit(:title, :category, :summary)
  end

  def set_story
    @story = Story.find(params[:id])
  end

end

这是 Postman 中的请求:

这是 Postman 中的输出:

我认为这是一个参数问题,但似乎不是。

【问题讨论】:

    标签: strong-parameters rails-api


    【解决方案1】:

    man 在第 3 行的帖子有效负载上有一个额外的左括号。 正确的 json 有效载荷是。:

    {
      "story": {
        "title": "Spiderman"
        "category": "Superhero"
        "summary": "new spiderguy ftw"
      }
    }
    

    我认为您的 story_params 方法存在问题。 Story 属性“title”、“category”和“summary”嵌套在“story”中。

    你可以试试这个:

    params.require(:story).permit(:title, :category, :summary)
    

    【讨论】:

    • 返回错误缺少参数:“#<:parametermissing: param is missing or value empty: story>”
    • 您的 POST 是否与邮递员的截图完全一样? {“故事”:{“标题”:“蜘蛛侠”,“摘要”:“超级英雄”,“类别”:“新蜘蛛侠ftw”}}
    • 是的。截图很准确。我也尝试过不嵌套故事:但得到的结果与传递空参数相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多