1

邀请.rb 为:

class Invitation < ApplicationRecord . 
  belongs_to :sender, class_name: 'User'
  belongs_to :subscription
end  

subscription.rb 为:

    class Subscription < ApplicationRecord
      has_many :payments, dependent: :destroy
      has_one :invitation, 
      belongs_to :plan
      belongs_to :user  
    end  

在邀请中添加列 subscription_id 的迁移文件如下:

    class AddSubscriptionIdToInvitations < ActiveRecord::Migration[5.1]
      def change
        add_reference :invitations, :subscription, foreign_key: true
      end
    end

虽然我没有在邀请模型中为订阅 ID 存在指定验证规则。但是当我执行以下代码时,出现错误“订阅不存在”:

    @invitation = Invitation.create_with(
          message: invitation_params.delete(:message),
          first_name: invitation_params.delete(:first_name),
          last_name: invitation_params.delete(:last_name),
        ).find_or_create_by(
          receiver: receiver,
          sender: current_user
        )  

Rails 版本 = 5.1.4 和 ruby​​ 版本 = 2.4.3。谢谢你。

4

2 回答 2

2

这是因为foreign_key: true. 您在数据库级别而不是在应用程序(模型)中遇到错误。

正如 Active Record 迁移 Rails 指南的外键Active Record 和参照完整性部分所述,您可以添加外键约束以保证参照完整性。Active Record 方式(验证)声称智能属于您的模型,而不是数据库。就像在应用程序级别运行的任何东西一样,这些不能保证引用完整性,这就是为什么您可能希望在数据库中使用外键约束(如果您希望关系始终存在)。

因此,如果您删除外键,您将不再收到错误消息。您可以使用remove_foreign_key.

于 2018-06-20T09:56:54.903 回答
0

从 rails 5 开始,belongs_to 具有选项“可选”,默认为 false,这就是为什么 belongs_to 关系默认具有存在验证。要删除验证,我们需要执行以下操作:-

class Invitation < ApplicationRecord . 
  belongs_to :sender, class_name: 'User'
  belongs_to :subscription, optional: true
end  
于 2018-06-26T05:57:05.270 回答