【问题标题】:ActionController::ParameterMissing (param is missing or the value is empty: properties):ActionController::ParameterMissing(参数丢失或值为空:属性):
【发布时间】:2020-11-10 03:57:07
【问题描述】:

我不断收到此消息 #<:parametermissing: param is missing or value empty: property>,只是不知道如何解决我所做的所有研究并将我的工作与我的工作进行比较。

我认为我的创建操作设置正确

def create
        raise params.inspect    
        @property = Property.create(prop_params)
       
         
        if @property.save!
            render json: @property
        else
            render json: { error: "Couldn't save"}
        end
    end

 def prop_params
        params.require(:property).permit(:address, :state, :sale_price, :owner_id)
 end

这是我的属性模型。

class Property < ApplicationRecord
    belongs_to :owner
    
end

当我执行 raise param.inspect 我得到了这个

Object { status: 500, error: "Internal Server Error", exception: "#<RuntimeError: <ActionController::Parameters {\"controller\"=>\"properties\", \"action\"=>\"create\"} permitted: false>>", traces: {…} }

我知道它应该显示我传递的内容,但在某些时候它只是停止显示我传递的内容并开始显示控制器和动作。

如何在前端提交表单?

listForm.addEventListener('submit',(event) =>{
     event.preventDefault();   
     
     const property = {
       address: document.getElementById('address').value,
       state: document.getElementById('state').value,
       sale_price: document.getElementById('sale_price').value,
       owner_id: document.getElementById('owner_id').value,
     }

     const listObj = {
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
          "Accept": "application/json"
      },
      body: JSON.stringify(property)
     }
      fetch(PROPERTIES_URL, listObj)
      .then(res => res.json())
      .then((list_data) => {
        let new_listing = renderListing(list_data)
        listings.append(new_listing)
        listForm.reset()
        console.log(list_data)
      })
  })

如何清除我的强大参数问题的障碍?

【问题讨论】:

    标签: javascript ruby-on-rails


    【解决方案1】:

    你得到的错误是 Rails 中强大的参数工作的结果。

    params.require(:property).permit(:address, :state, :sale_price, :owner_id)
    

    上面这行告诉 Rails 你希望以这种形式接收你的参数:

    {
      property: {
        address: "123 city st",
        state: "NSW",
        sale_price: 100.00,
        owner_id: 1
      }
    }
    

    注意 require(:property) 部分告诉 Rails 你想要接收的参数需要有键“property”。在属性键内部,您告诉它允许其余键(:address、:state、:sale_price、:owner_id)。

    修复代码的最简单解决方案是通过更改此行来更改从前端发送的正文以匹配所需的格式:

    // Before
    body: JSON.stringify(property)
    // After
    body: JSON.stringify({ property })
    

    您可以阅读更多关于强参数here

    【讨论】:

    • 不幸的是,这个应用程序被诅咒了,因为它对我不起作用。但按照你解释的方式,它是有道理的。其他人一度暗示同样的事情。我仍然不断收到消息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2021-11-20
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多