两个模型之间的 Rails ActiveRecord 关系具有相同的列



我有 2 个模型 - 人,电子邮件订阅

人物

class CreatePeople < ActiveRecord::Migration[6.0]
def change
create_table :people do |t|
t.integer :store_customer_id
t.string :email
end
end
end

email_subscriptions

class CreateEmailSubscriptions < ActiveRecord::Migration[6.0]
def change
create_table :email_subscriptions do |t|
t.integer :email_subscription_type_id
t.integer :store_customer_id
end
end
end

关系

Person.store_customer_id = EmailSubscription.store_customer_id

我是如何做到的

class Person < ApplicationRecord
def email_subscription
EmailSubscription.where(store_customer_id: store_customer_id).first
end
end
class EmailSubscription < ApplicationRecord
def person
Person.where(store_customer_id: store_customer_id).first
end
end

有没有更好的解决方案?

谢谢。

你不应该把person_id放在people表中。

因为people的主键是人的ID。

所以对于人员表:

class CreatePeople < ActiveRecord::Migration[6.0]
def change
create_table :people do |t|
t.string :email
end
end
end

为了使关系发生,您应该使用人员表的外键实现email_subscribtions表:

class CreateEmailSubscriptions < ActiveRecord::Migration[6.0]
def change
create_table :email_subscriptions do |t|
t.integer :email_subscription_type_id
t.references :person, foreign_key: true
end
end
end

在此处查看导轨参考。

在模型中,您只需添加:

class Person < ApplicationRecord
has_one :email_subscription
end
class EmailSubscription < ApplicationRecord
belongs_to :person
end

这只会给你acrive_record联想的力量:

@person.email_subscription
@email_subscription.person

您没有明确说明为什么需要将此类方法添加到模型类中

def email_subscription
EmailSubscription.where(person_id: person_id).first
end

我想相信email_subscriptionbelongs_to personpeople has_many: email_subscriptions如果您想要访问或获取belongs_to特定人员的email_subscription,那么self.email_subcriptions将返回属于当前人员的订阅,对于email_subscription类,您可以添加self.person。也许您可以使用范围而不是方法,但我觉得您也可以直接在控制器中调用它。

最新更新