3

我无法通过关联从 has_many 验证模型。以下是相关型号:

广播模型

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

还与拥有_many 通过广播收据的广播收据的用户相关联。

问题似乎与以下行有关:

validates :broadcast_id         , presence: true

每当我尝试创建广播时,我都会得到回滚,但没有给出错误消息。但是,当删除上述行时,一切都按预期工作。

这看起来像是在创建广播收据之前未保存广播的问题。
有什么方法可以验证在收据模型上设置了 broadcast_id 吗?

4

2 回答 2

2

这似乎与此处讨论的问题相同:https ://github.com/rails/rails/issues/8828 ,已通过将 :inverse of 添加到连接模型的 has_many 关联中来解决。

于 2013-07-20T13:43:00.367 回答
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
于 2013-02-07T10:27:12.693 回答