让我说我将数组保存到我的模型中。有没有办法为它添加属性?
我正在运行Property.create(property_params)
以将数组的实例保存到我的模型中
是否有额外的属性附加到property_params
但未在json中传递?假设我想将创建方法中设置的全局变量currentuserid
传递给.create
,并将其与user_id
一起保存到模型property_params
中的属性中?
我尝试在property_params上使用.merge
,但它没有用。我想我需要将它传递给数组?
这可能吗?
def create
currentuserid = 4
property_items = PropertyItem.create(property_params)
end
private
def property_params
params.permit(property: [:houses, :id, :father, :mother, :height, :children, :pets]).require(:property)
end
这是我的json:
"property":[
{
"houses":"1",
"id":"5",
"father":"Jerry",
"mother":"Tanya",
"height":281,
"children":2,
"pets":24
},
{
"houses":"3",
"id":"5",
"father":"Rob",
"mother":"Anne",
"height":726,
"children":1,
"pets":55
}
]
}
答案 0 :(得分:1)
找到答案here,您可以使用合并
将其插入参数定义中private
def property_params
params.require(:property).permit(:some_attribute).merge(user_id: current_user.id)
end
或
def create
@property_items = PropertyItem.create(property_params)
@property_items.currentuserid = 4
#...
end
答案 1 :(得分:0)
了解您正在尝试做什么,如何在模型中处理此问题以及为什么要尝试这样做会有所帮助。
当你require(:property)
时,结果是数据结构嵌套了比:property
更深的一层,这是一个params哈希数组。这就是为什么你不能merge
或permit
之后致电require
的原因。因为数组不会对这些方法做出响应。如果PropertyItem
是ActiveRecord
个对象,那么您将很难将数组传递给create
并让它发挥作用。
hash = {
"property" => [
{
"houses" => "1",
"id" => "5",
"father" => "Jerry",
"mother" => "Tanya",
"height" => 281,
"children" => 2,
"pets" => 24
},
{
"houses" => "3",
"id" => "5",
"father" => "Rob",
"mother" => "Anne",
"height" => 726,
"children" => 1,
"pets" => 55
}
]
}
params = ActionController::Parameters.new(hash)
# => <ActionController::Parameters {"property"=>[{"houses"=>"1", "id"=>"5", "father"=>"Jerry", "mother"=>"Tanya", "height"=>281, "children"=>2, "pets"=>24}, {"houses"=>"3", "id"=>"5", "father"=>"Rob", "mother"=>"Anne", "height"=>726, "children"=>1, "pets"=>55}]} permitted: false>
params.permit(property: [:houses, :id, :father, :mother, :height, :children, :pets]).require(:property)
# => [<ActionController::Parameters {"houses"=>"1", "id"=>"5", "father"=>"Jerry", "mother"=>"Tanya", "height"=>281, "children"=>2, "pets"=>24} permitted: true>, <ActionController::Parameters {"houses"=>"3", "id"=>"5", "father"=>"Rob", "mother"=>"Anne", "height"=>726, "children"=>1, "pets"=>55} permitted: true>]
首先将currentuserid
合并到params中,然后只调用permit
而不require
,这样就可以获得我认为您正在寻找的内容。
params.merge(currentuserid: 1).permit(:currentuserid, property: [:houses, :id, :father, :mother, :height, :children, :pets])
# => <ActionController::Parameters {"currentuserid"=>1, "property"=>[<ActionController::Parameters {"houses"=>"1", "id"=>"5", "father"=>"Jerry", "mother"=>"Tanya", "height"=>281, "children"=>2, "pets"=>24} permitted: true>, <ActionController::Parameters {"houses"=>"3", "id"=>"5", "father"=>"Rob", "mother"=>"Anne", "height"=>726, "children"=>1, "pets"=>55} permitted: true>]} permitted: true>
但我认为一个重要的问题仍然是你究竟想做什么,为什么?