【发布时间】:2019-03-14 22:59:51
【问题描述】:
我有三个模型:User、Company 和 Subscription。我想要完成的是Subscription 属于User 或Company。
为了尝试实现这一点,我引用了this guide,但由于记录创建不断回滚,我没有成功。
这是我的Company 模型:
# app/models/company.rb
class Company < ApplicationRecord
has_many :subscriptions, dependent: :destroy, as: :imageable
end
这是我的User 模型:
# app/models/user.rb
class User < ApplicationRecord
has_many :subscriptions, dependent: :destroy, as: :imageable
end
最后,这是我的Subscription 模型:
class Subscription < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
现在就迁移文件而言,这是我的Subscription 迁移文件:
class CreateSubscriptions < ActiveRecord::Migration[5.1]
def change
create_table :subscriptions do |t|
t.references :imageable, polymorphic: true, index: true
t.date :start_date
t.date :stop_date
t.timestamps
end
end
end
据我所见,这与指南显示的非常相似,但它一直在回滚。这是 rails 控制台的输出:
Loading development environment (Rails 5.1.6)
2.5.1 :001 > Subscription.create(imageable_id: 1, start_date: Time.now, stop_date: 2.days.from_now)
(8.6ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
(0.2ms) BEGIN
(0.3ms) ROLLBACK
=> #<Subscription id: nil, imageable_type: nil, imageable_id: 1, start_date: "2018-10-10", stop_date: "2018-10-12", created_at: nil, updated_at: nil>
2.5.1 :002 >
以下是我的问题:
- 为什么会有
imageable_type字段?这是由t.references创建的,如果是,我需要这个吗?我可以只使用imageable_id而不是t.references,就像建议的另一部分显示的那样吗? - 为什么会回滚?多态关联是在 Rails 5.x 中以不同方式完成的还是偶然的?
- 根据指南中显示的图表,如果一张图片属于
imageable_id4,那么如果有一个员工和一个 ID 为 4 的生产,那么一张图片将属于两者而不是一个或其他我想要完成的事情。正确吗?
【问题讨论】:
-
您可以像
User.first.subcriptions.create(start_date: Time.now, stop_date: 2.days.from_now)那样创建订阅,而不是像这样创建订阅,所以它会自动采用 imagable id 和 imageble type -
啊,好的。这是有道理的,所以
imageable_type实际上显示了正确的引用,因此 Company 和 User 的 ID 为 1 将通过其imageable_type进行区分,对吗? -
是的,让我补充一下答案
-
明白了。谢谢!现在说得通了。
标签: ruby-on-rails activerecord