简体   繁体   English

Rails 4-将ID转换为参数模型

[英]Rails 4 - Convert id to model in params

My code is errorring out when I try to insert a new record in the DB: 当我尝试在数据库中插入新记录时,我的代码出错了:

@user_request = UserRequest.new(user_request_params)

I have a model that belongs to another. 我有一个属于另一个模型。 The user selects the sub model in a dropdown, and the id is sent in json: 用户在下拉列表中选择子模型,并且ID以json发送:

{"user_request"=>{"product_ids"=>["86", "79"], "sub_model_id"=>"5"}

Schema 架构

UserRequest
  has_and_belongs_to_many :products
  has_one :sub_model

SubModel
  belongs_to :user_request

Product
  has_and_belongs_to_many :user_requests

The product is inserted into the db no problem (if I ignore the submodel), but the SubModel is not. 将产品插入db没问题(如果我忽略了子模型),但是SubModel却没有。 I get this error: 我收到此错误:

ActiveRecord::UnknownAttributeError (unknown attribute: sub_model_id):
  app/controllers/user_requests_controller.rb:44:in `create'

I tried to edit the params before hand by doing this: 我尝试通过执行以下操作来预先编辑参数:

def user_request_params
    params.require(:user_request).permit(:sub_model_id, :product_ids => [])
    #the above line was there, added these lines:
    sub_id = params[:user_request][:sub_model_id]
    sub = SubModel.find(sub_id)
    params[:user_request].delete(:sub_model_id)
    params[:user_request][:sub_model] = sub
    params
end

which generates the following JSON: 生成以下JSON:

{"user_request"=>{"product_ids"=>["86", "79"], "sub_model"=>#<SubModel id: 5, ...} 

but now I get this error: 但是现在我得到这个错误:

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

app/controllers/user_requests_controller.rb:42:in `create' app / controllers / user_requests_controller.rb:42:在'create'中

The submodel's were generated before hand by the admin of the site (they do exist). 子模型是由站点的管理员事先生成的(它们确实存在)。

How do I get the UserRequest to save? 如何获取UserRequest保存?

UserRequest table doesn't have sub_model_id column in DB, so it raise your error. UserRequest表在数据库中没有sub_model_id列,因此会引发错误。 Specify it in migration and swap associations: 在迁移和交换关联中指定它:

UserRequest
  has_and_belongs_to_many :products
  belongs_to :sub_model

SubModel
  has_one :user_request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM