Rails 3.1 无法使用 has_one 创建:来自 Rails 控制台的多态模型 [英] Rails 3.1 Unable to create with has_one :polymorphic model from rails console

查看:33
本文介绍了Rails 3.1 无法使用 has_one 创建:来自 Rails 控制台的多态模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

class MenuItem < ActiveRecord::Base
    has_one :price, :as => :pricable
    accepts_nested_attributes_for :price
    attr_accessible :price_attributes, :price
end

class Price < ActiveRecord::Base
    belongs_to :pricable, :polymorphic => true
    attr_accessible :price, :price_comment
end

我正在尝试使用以下命令插入 rails 控制台:

I'm trying to insert at rails console with:

MenuItem.create({"name"=>"Julie's Mac & Cheese","price"=>{"price"=>14}})

但我收到此错误:

ActiveRecord::AssociationTypeMismatch: Price(#70145189558680) expected, got Hash(#70145158648700)

我如何强迫它认为这是一个价格?尝试使用它作为符号

How do I force this into thinking it is a Price? tried using it as symbol

谢谢?

推荐答案

MenuItem.create(:name => "Julie's Mac & Cheese", :price_attributes => {:price => 14})

edit 抱歉没有解释,但答案很简单……你只是没有传递正确的参数.我也清理了一下.

edit Sorry for lack of explanation but the answer is pretty simple... you just weren't passing the right parameter. I also cleaned it up a bit.

这篇关于Rails 3.1 无法使用 has_one 创建:来自 Rails 控制台的多态模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆