Rails has_many:通过验证

时间:2013-02-07 09:59:11

标签: ruby-on-rails validation has-many-through

我无法通过关联验证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

还有一个与用户有关联,通过广播收据广播收据。

问题似乎在以下一行:

validates :broadcast_id         , presence: true

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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