运行我的create方法时ActiveRecord :: AssociationTypeMismatch错误?

时间:2015-09-01 12:34:57

标签: ruby-on-rails ruby ruby-on-rails-4

我一直试图让它工作一段时间,但不断收到以下错误:

ActiveRecord::AssociationTypeMismatch
Category(#70314437722040) expected, got String(#14075760)

我有一个Post模型,其中包含对另一个Category模型的引用。我正在尝试使用以下格式保存新帖子(使用haml& simple_form gems):

= simple_form_for @post do |f|
  = f.input :title
  = f.input :content
  = f.input :category, collection: @category 
  #(defined in new method >>>@category = Category.all.order('title'))
  = f.submit
下面的

是我控制器中的create方法:

def create
  @post = current_user.posts.build(post_params) #<<<error here
  @post.save    
end
.
.
private

def post_params
  params.require(:post).permit(:title, :content, :category)
end

1 个答案:

答案 0 :(得分:1)

更改您的表单(我将@category重命名为@categories):

= simple_form_for @post do |f|
  = f.input :title
  = f.input :content
  = f.input :category_id, collection: @categories, label_method: :name, value_method: :id
  = f.submit

同样在控制器中:

def post_params
  params.require(:post).permit(:title, :content, :category_id)
end

代码中的错误与事实有关,默认情况下,SimpleForm将集合视为字符串数组。因此,:category参数的值为String,而Category则为class asset_asset(osv.osv): _inherit = "asset.asset" #_name = "asset_asset" _rec_name= "folio_num" _columns = { 'name': fields.char('Asset Name', size=64), 'company_id1': fields.many2one('res.company', 'Company', required=True), 'place1': fields.many2one('asset.parentlocation', 'Location'), 'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',select=True, required=True), 'area_id' : fields.many2one('asset.name', 'Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True), 'assetmodelid_add' : fields.many2one('agile.portfolio1','Asset Model Code',domain="[('area_id', '=', area_id)]",), 'folio_num' : fields.char('Folio No',), 'asse_line':fields.one2many('asset.line','emp_id','Name Plate'), 'asse_line2':fields.one2many('asset.part','emp_id1','Parts'), #'assed_modelid':fields.many2one('agile.portfolio1','Asset Model ID',select=True, required=True), 'quantity': fields.char('Quantity',size=64), 'uom': fields.char('Uinit of Measure',size=64), 'model_no' : fields.char('Model', size=64), #'asset_id':fields.many2one('agile.portfolio','Asset ID'), }