Rails has_many :through验证

3

我在验证一个具有has_many through关联的模型时遇到了困难。以下是相关模型:

Broadcast模型

class Broadcast < ActiveRecord::Base

    attr_accessible :content,
                    :expires,
                    :user_ids,
                    :user_id

    has_many :users, through: :broadcast_receipts
    has_many :broadcast_receipts, dependent: :destroy

    validates :user_id, presence: true
    validates :content, presence: true

end

广播收据模型

class BroadcastReceipt < ActiveRecord::Base

    belongs_to :broadcast
    belongs_to :user

    attr_accessible :user_id, :cleared, :broadcast_id

    validates :user_id      , presence: true
    validates :broadcast_id         , presence: true
end

还有一个与用户相关的关联,这些用户通过广播接收到许多广播收据。

问题似乎出现在以下代码行中:

validates :broadcast_id         , presence: true

每当我尝试创建广播时,都没有错误消息就回滚了。但是,如果删除上述行,则一切正常。
这看起来像是在创建广播收据之前未保存广播的问题。
有没有办法验证收据模型上是否设置了广播ID?

你可以创建一个自定义验证器,类似于:validate :broadcast_id_exists,并在你的验证中检查广播是否存在于数据库中。 - Kaeros
2个回答

2

1

你的代码结构可能存在问题。你可以尝试使用这个版本。

class Broadcast < ActiveRecord::Base
  # I assume these are the recipients
  has_many :broadcast_receipts, dependent: :destroy
  has_many :users, through: :broadcast_receipts

  # I assume this is the creator
  validates :user_id, :content, presence: true
  attr_accessible :content, :expires, :user_id, :user_ids
end

class BroadcastReceipt < ActiveRecord::Base
  belongs_to :broadcast
  belongs_to :user

  # You should be able to validate the presence
  # of an associated model directly
  validates :user, :broadcast, presence: true

  attr_accessible :cleared
end

我知道这个代码为什么应该能够工作,但实际上它却没有运行成功,也没有报错。有趣的是,在升级到Rails 3.2.11之前,它曾经可以正常运行,但我无法在更新日志中找到任何可能导致它停止工作的原因。代码仍然试图在广播保存之前先保存收据,因此它没有可传递的broadcast_id。 - Ammar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接