【问题标题】:Rails association has_one has inverse behavior than expectedRails 关联 has_one 的行为与预期相反
【发布时间】:2016-03-11 20:37:16
【问题描述】:

我刚刚添加了一个新模型Intent 来保存有关想要购买我们产品和服务的用户的信息。

所以我将ProductServiceUser 的ID 保存在此表intent 中。

我创建了一个迁移来引用 Intent 中的外键,然后添加了以下关联

belongs_to :user
has_one :product
has_one :service

我希望 Rails 在 Intent 中搜索 product_idservice_id,但情况正好相反:

Mysql2::Error:“where 子句”中的未知列“products.intent_id”: ...

我该如何解决?我是否选择了错误的关联类型?

【问题讨论】:

  • 为什么不属于产品/服务?为什么has_one?

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


【解决方案1】:

听起来你需要:

belongs_to :user
belongs_to :product
belongs_to :service

然后在user.rb 中添加has_many :intents,在product.rbservice.rb 中添加has_one :intent

我记得has_one 的方式是它替换了has_many,所以你可以把它放在你通常放在has_many 的任何地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多