如何在Rails中使用参数?

时间:2019-07-08 09:24:14

标签: ruby-on-rails parameters

我有一个后置控制器,用于保存具有不同属性的帖子。帖子上还有附件。这些附件仅返回对象的ID。 my_cards my_folders other_cards other_folders 都是此类字段。这些在模型中定义为数组。

我正在通过如下所示的表格传递正确的参数。存在所有正确的数据。

PARAMS

{"_id"=>"", "title"=>"Test Post Card attach 28", "description"=>"", 
"privacy"=>"public", "url_ids"=>"", "image_ids"=>"", 
"attached_card_ids"=>"", "my_card_ids"=>:my_card_ids, 
"my_folder_ids"=>"5d21dc7c616b656a9c030000", 
"other_card_ids"=>"5d1b1942616b656d10360000", 
"other_folder_ids"=>"5cfe2bdf69702d0aa3010200", "domain"=>"localhost", 
"controller"=>"api/v1/posts", "action"=>"create", 
"owner_id"=>"5d125102616b657131020000", 
"user_id"=>"5d125102616b657131020000"}

但是当我保存帖子时,即使认为它们在post_params方法中被定义为数组,post_params方法也会将某些字段标记为不允许。

POST-PARAMS

Unpermitted parameters: _id, url_ids, image_ids, attached_card_ids, 
my_card_ids, other_card_ids, other_folder_ids, domain
{"title"=>"Test Post Card attach 28", "privacy"=>"public", 
"description"=>"", "owner_id"=>"5d125102616b657131020000", 
"user_id"=>"5d125102616b657131020000", "my_folder_ids"=>nil}

我的post_params方法看起来像这样

def post_params
  params.permit(:id, :title, :privacy, :description, 
   :owner_id,:user_id,
   :url_ids => [], :image_ids => [], :attached_card_ids => [],
   my_card_ids: [], my_folder_ids: [],
   :other_card_ids => [], :other_folder_ids => [])
end

在研究了其他堆栈溢出问题之后,我尝试了多种方法在post_params方法中定义数组。

编辑

我设法将记录保存在Mongo数据库中。属性看起来像这样。

"my_card_ids" : [
        "5d1b83a6616b6523a9020000,5d1b9893616b653abd0b0000"
], 
"my_folder_ids" : [
        "5d21dc7c616b656a9c030000"
], 
"other_card_ids" : [
        "5d1b168c616b656d10140000"
], 
"other_folder_ids" : [
        "5cfe2bdf69702d0aa3010200"
]

它们被存储为字符串,我该如何将它们另存为ID

"collections" : [ 
        ObjectId("5d125102616b657131020000"),
]

1 个答案:

答案 0 :(得分:3)

是否可以添加用于发布表单数据的表单的HTML。

您在上方显示的参数显示

"my_folder_ids"=>"5d21dc7c616b656a9c030000", 
 "other_card_ids"=>"5d1b1942616b656d10360000", 
"other_folder_ids"=>"5cfe2bdf69702d0aa3010200"

作为字符串。在控制器中,当您将它们作为纯字符串发送时,已经允许它们作为数组。

要解决此问题,字段的html名称属性必须为name="my_folder_ids[]"而不是name=my_folder_id