【问题标题】:Passing Post request through postman for has_many association in rails通过邮递员为rails中的has_many关联传递Post请求
【发布时间】:2017-10-19 19:10:02
【问题描述】:

我是新手,需要一些帮助。我有两个模型(通过脚手架生成)。类别和产品。

  class Category
   include Mongoid::Document
   field :name, type: String

   has_many :products
   accepts_nested_attributes_for :products
 end

 class Product
   include Mongoid::Document
   include Mongoid::Paperclip
   include Mongoid::Timestamps::Created

   field :name, type: String
   field :description, type: String
   field :prize ,type: Integer
   field :category_id
   field :user_id

has_mongoid_attached_file :avatar,
  :styles => {
      :thumb => "150x150#",
      :small  => "150x150>",
      :medium => "550x550#{}" }

belongs_to :user
belongs_to :category
end

我的类别控制器

# POST /categories.json

 def create
    @category = Category.new(category_params)


    respond_to do |format|
      if @category.save
        format.html { redirect_to @category, notice: 'Category was successfully created.' }
        format.json { render :show, status: :created, location: @category }
      else
        format.html { render :new }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end

    end


 def category_params
      params.require(:category).permit(:name,product_attributes: [ :name, :description,:prize ,:category_id])
    end

  end

我的json格式

{

    "name":"Mens Clothing",
    "products_attributes": [
        {

            "name":"Denim jeans",
            "Description": "test test test"
            "prize":1000,
            "user_id":1,
        }
    ]
}

现在我的问题是,当我尝试通过邮递员访问 localhost:3000/categories 时,值没有得到保存。另外我不知道我的 json 格式是否正确,或者我的类别控制器代码是否正确。我是新来的,并试图弄清楚如何以 json 格式保存 rails.iam 中 has_many 关系的数据丢失参数错误

【问题讨论】:

    标签: ruby-on-rails json ruby postman


    【解决方案1】:

    您需要将基本资源名称作为 JSON 中的键:

    {"category": {
    
        "name":"Mens Clothing",
        "products_attributes": [
            {
    
                "name":"Denim jeans",
                "Description": "test test test", # <== Added a comma here
                "prize":1000,
                "user_id":1,
            }
        ]
    }}
    

    params.require(:category) 表示您要查看传入参数并拉取:category 键的值,如果找不到该键,则会引发ActionController::ParameterMissing 异常。

    如果找到:category 键,则将其值传递给#permit,这会过滤掉任何未包含在批准列表中的键。

    因为您的参数中没有:category,所以您的日志应该反映ActionController::ParameterMissing 异常。

    【讨论】:

    • 谢谢#moveson。但我仍然收到此错误。ActionController::ParameterMissing(参数丢失或值为空:类别):
    • 请编辑您的问题以显示从“started POST /categories”开始到“Completed xxx in xxxms”结束的完整服务器日志。
    • 谢谢,问题已解决,实际上我试图从邮递员那里获取数据。在更改控制器创建操作的一些更改时,我得到了我想要的。你的回答给了我解决方案的路线图。
    猜你喜欢
    • 2017-12-30
    • 2017-02-09
    • 2014-10-24
    • 1970-01-01
    • 2018-06-25
    • 2016-09-17
    • 2019-04-28
    • 2021-12-11
    • 2018-12-09
    相关资源
    最近更新 更多