【发布时间】:2020-11-14 21:37:13
【问题描述】:
以我当前发送到后端的对象为例...
{"owner_id":"Rocky","address":"Test","state":"Test","sale_price":"Test"}
但我的意图是这样寄回去
{"owner_id": 1, "address":"Test","state":"Test","sale_price":"Test"}
问题是....键“owner_id”应该是 Rocky 的 id 整数,而我的后端不会保存它,因为“owner_id”应该是整数而不是字符串。
为了澄清本说明的下一部分,我从前端的下拉列表中选择一个名称,顺便说一句,ID 为“owner_id”。
我的所有者名称删除设置如下:
let dropdown = document.getElementById('owner_id');
dropdown.innerHTML= `` //disappear
fetch(OWNERS_URL)
.then(resp => resp.json())
.then(owners => {
owners.forEach(owner => {
dropdown.innerHTML += `<option data-id = ${owner.id} = ${owner.id}>${owner.name}</option>`
})
})
您会注意到我将 data-id 属性设置为 owner.id 以将该选项与名称相关联,当我查看我的检查器时我的开发工具选项元素按预期设置
<option data-id="1">Rocky</option>
下面是处理提交房产清单的代码(尽管我认为这可能无关紧要
function ListForm(){
let owner_id = document.getElementById('owner_id').value
let address = document.getElementById('address').value
let state = document.getElementById('state').value
let sale_price = document.getElementById('sale_price').value
const listing = {
owner_id: owner_id,
address: address,
state: state,
sale_price: sale_price
}
// const formData = new FormData(listForm)
const listObj = {
method: 'POST',
body: JSON.stringify(listing),
headers: {
"Accept": "application/json"
}
}
fetch(PROPERTIES_URL, listObj)
.then(res => res.json())
.then((listing) => {
let new_listing = renderListing(listing)
listings.append(new_listing)
console.log(new_listing)
})
}
listForm.addEventListener('submit',(event) =>{
event.preventDefault();
ListForm()
listForm.reset()
})
这也是我的属性控制器在后端创建操作以及它的架构。
def create
property = Property.create(prop_params)
if property.save
render json: property
else
render json: { error: "Couldn't save"}
end
end
def prop_params
params.permit(:id, :address, :state, :sale_price, :owner_id, owner_attributes: [:id, :name, :phone_number,:real_estate_agent])
end
#架构
create_table "properties", force: :cascade do |t|
t.integer "owner_id"
t.string "address"
t.string "state"
t.string "sale_price"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
我需要在我的代码库中做些什么或对其进行更改才能获得最初提到的我正在寻找的结果?
【问题讨论】:
-
option tags 有一个
value属性。
标签: javascript html ruby-on-rails