ruby-on-rails - 参数缺失或值为空 : company

标签 ruby-on-rails json ruby

我正在尝试让这个 API 正常工作,但遇到了这个我不知道如何解决的错误。我在标题上收到错误。我使用了来自谷歌浏览器的 postman 扩展。并尝试执行发布请求在

localhost:3000/companies

并得到一个错误。如下图所示

ActionController::ParameterMissing in CompaniesController#create param is missing or the value is empty: company

def company_params
 (this line is highlighted) params.require(:company).permit(:name, :phone, :email, :website, :address, :customer_id, :additional_info)
end
end
   Request

Parameters:

{"name"=>"harun"}

我已经生成了一个 rails-api,添加了 avtive_model_serializerrack-cors gem。为 cors 修改了 config/application

然后为公司生成一个脚手架。

gem 文件

gem 'active_model_serializers', '~> 0.10.0'
gem 'rack-cors'

config/application.rb

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

app/serializers/company_serializer.rb

class CompanySerializer < ActiveModel::Serializer
 attributes :id, :name, :phone, :email, :website, :address, :customer_id, :additional_info
end

controllers/companies_controller.rb

class CompaniesController < ApplicationController
  before_action :set_company, only: [:show, :update, :destroy]
  def index
    @companies = Company.all
    render json: @companies
  end

  def show
    render json: @company
  end

  def create
    @company = Company.new(company_params)
    if @company.save
      render json: @company, status: :created, location: @company
    else
      render json: @company.errors, status: :unprocessable_entity
    end
  end

  def update
    @company = Company.find(params[:id])

    if @company.update(company_params)
      head :no_content
    else
      render json: @company.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @company.destroy

    head :no_content
  end

  private

    def set_company
      @company = Company.find(params[:id])
    end

    def company_params
      params.require(:company).permit(:name, :phone, :email, :website, :address, :customer_id, :additional_info)
    end
end

最佳答案

您正在传递参数 {"name"=>"harun"} 您需要传递 {"company"=> { "name"=>"harun"} } .

在 postman 中(如果你发送的是 json 数据)发送这个数据:

{"company":{"name":"harun"}}

如果您要发送表单数据,请发送:

company[name] = "harun"

使用强参数,当找不到所需参数时会出现错误:

params.require(:company)

关于ruby-on-rails - 参数缺失或值为空 : company,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907919/

相关文章:

html - 为什么我的网站没有使用我指定的字体?无法访问字体?

python - 如何将 Cisco IOS 输出解析为对象或 JSON

javascript - 无法在 Typescript 中为对象属性设置值。无法设置未定义的属性 'ismain'

json - ElasticSearch:获取嵌套字段的所有值

ruby-on-rails - rails : Validate input without need of models

ruby-on-rails - 更改主要关键问题 Rails 4.0

css - Rails] 使用 current_page 方法开启 CSS Class Active

ruby - 检查字符串是否包含 Ruby 中的特定字符序列

javascript - axios POST 请求(javascript)和 Sinatra/Base API(ruby)的问题

ruby - 使用 rvm 在 Ubuntu 12.4 中安装 ruby​​ 时缺少 lib 'libruby.so.1.9' 错误