我仍然在学习Rails,在我的应用程序中,当用户创建假期请求时,我正在尝试实现发送给admin的通知。我正试图跟进两种解决方案,大致相同-- 简易通知系统是受克里斯·奥利维尔的肚脐通知启发的,我被困在了一开始。当用户试图创建假期请求时,我收到了一个错误:
未定义方法`marked_for_destruction?‘假:FalseClass
我试着在控制器中定义这个方法,但是它没有起作用。
leave.rb模型:
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
enduser.rb模型:
class User < ApplicationRecord
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :notifications, foreign_key: :recipient_id
has_many :leaves, dependent: :destroy
end叶控制器:
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
但也没用。
任何提示都欢迎。
发布于 2018-10-22 15:04:18
如果我完全理解您的通知系统,那么每次创建Leave时,您都会尝试向admins发送一个通知。
假设您的错误来自您的recipients方法:[user.admin]返回[true]或[false]
当你迭代它的时候,你需要:Notification.create(recipient: true/false, ...)
您可以通过为管理员创建用户范围来修复系统:
class User < ApplicationRecord
#...
scope :admins, -> { where(admin: true) }
end并更改recipients方法,如:
class Leave < ApplicationRecord
#...
private
def recipients
User.admins
end
def create_notifications
#...
end
end发布于 2018-10-21 17:01:28
如果您使用查看存在验证器的代码。,您将看到它遍历一个Enumerable并对其元素调用marked_for_destruction?。
查看您的代码,这表明您试图分配给关联的值之一是false,而不是您所期望的ActiveRecord对象。
要调试这个问题,我建议签出刺探和pry-byebug gem:使用它,您可以在Notification.create之前向行中添加一个断点(binding.pry),并签出recipient和self.user的值。
https://stackoverflow.com/questions/52910284
复制相似问题