2017-10-19 96 views
0

我是一个新的学习者,需要一些帮助。我有两个模型(我通过脚手架生成)。类别和产品。通过邮递员通过邮递员的has_many协会在轨道上

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, 
     } 
    ] 
} 

现在的问题是,当我试图打本地主机:3000 /类别通过邮递员值不会得到保存。另外我不知道我的json格式是否正确,或者我的类别控制器代码是否正确。我是新的,并试图弄清楚如何将数据保存在JSON格式的has_many关系在rails.iam越来越缺少PARAMS错误

回答

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例外。

+0

谢谢#moveson。但我仍然得到这个error.ActionController :: ParameterMissing(param丢失或值为空:类别): –

+0

请编辑您的问题,以显示从“开始的POST /类别“并以”在xxxms中完成xxx“结束。 – moveson

+0

感谢人,问题实际上是解决了,我试图从邮递员处获取数据。并且改变控制器的一些更改创建操作,我得到了我想要的。您的答案为我提供了解决方案的路线图。 –