首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >`marked_for_destruction?假:FalseClass

`marked_for_destruction?假:FalseClass
EN

Stack Overflow用户
提问于 2018-10-20 21:30:29
回答 2查看 816关注 0票数 0

我仍然在学习Rails,在我的应用程序中,当用户创建假期请求时,我正在尝试实现发送给admin的通知。我正试图跟进两种解决方案,大致相同-- 简易通知系统是受克里斯·奥利维尔的肚脐通知启发的,我被困在了一开始。当用户试图创建假期请求时,我收到了一个错误:

未定义方法`marked_for_destruction?‘假:FalseClass

我试着在控制器中定义这个方法,但是它没有起作用。

leave.rb模型:

代码语言:javascript
复制
class Leave < ApplicationRecord

after_create :create_notifications
belongs_to :user, optional: true

private

def recipients
[user.admin]
end

def create_notifications
recipients.each do |recipient|
  Notification.create(recipient: recipient, actor: self.user,
    action: 'posted', notifiable: self)
end
end

user.rb模型:

代码语言:javascript
复制
class User < ApplicationRecord
devise :invitable, :database_authenticatable, :registerable,
     :recoverable, :rememberable, :validatable

has_many :notifications, foreign_key: :recipient_id
has_many :leaves, dependent: :destroy
end

叶控制器:

代码语言:javascript
复制
def create
@leave = Leave.new(leave_params)
@user = User.new


if @leave.save
  redirect_to leaves_path
else
  render :new
end
end

我想我必须把'autosave: true'添加到has_many中,

它应该看起来像has_many :leaves, dependent: :destroy, autosave: true

但也没用。

任何提示都欢迎。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-22 15:04:18

如果我完全理解您的通知系统,那么每次创建Leave时,您都会尝试向admins发送一个通知。

假设您的错误来自您的recipients方法:[user.admin]返回[true][false]

当你迭代它的时候,你需要:Notification.create(recipient: true/false, ...)

您可以通过为管理员创建用户范围来修复系统:

代码语言:javascript
复制
class User < ApplicationRecord
  #...
  scope :admins, -> { where(admin: true) }
end

并更改recipients方法,如:

代码语言:javascript
复制
class Leave < ApplicationRecord
  #...
  private

  def recipients
    User.admins
  end

  def create_notifications
    #...
  end
end
票数 1
EN

Stack Overflow用户

发布于 2018-10-21 17:01:28

如果您使用查看存在验证器的代码。,您将看到它遍历一个Enumerable并对其元素调用marked_for_destruction?

查看您的代码,这表明您试图分配给关联的值之一是false,而不是您所期望的ActiveRecord对象。

要调试这个问题,我建议签出刺探pry-byebug gem:使用它,您可以在Notification.create之前向行中添加一个断点(binding.pry),并签出recipientself.user的值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52910284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档