我正在尝试为特定用户的关注者设置通知,以便每当他们关注的用户发布一章时,所有用户的关注者都会收到通知。我正在使用https://github.com/rails-engine/notifications。
根据本教程https://www.devwalks.com/lets-build-instagram-with-ruby-on-rails-part-6-follow-all-the-people/
,我实现了以下关系,这些关系在我的应用程序上运行良好这是我到目前为止对代码所做的
user.rb
has_many :books, dependent: :destroy
has_many :chapters, dependent: :destroy
has_many :reviews, dependent: :destroy
has_many :genres
has_many :ratings
chapter.rb
belongs_to :book
belongs_to :user
after_commit :create_notifications, on: :create
private
def create_notifications
Notification.create do |notification|
notification.notify_type = 'chapter'
notification.actor = self.book.user
notification.user = self.user.followers
notification.target = self
notification.second_target = self.book
end
end
views / notifications / _chapter.html.erb
<div class=''>
<%= link_to notification.actor.username, main_app.profile_path(notification.actor.username) %> published a new chapter to
<%= link_to notification.second_target.title, main_app.book_path(notification.second_target) %>
</div>
<div class=''>
<% unless notification.target.blank? %>
<%= link_to notification.target.title, main_app.book_chapter_path(notification.second_target, notification.target.id) %>
<% end %>
</div>
book.rb
belongs_to :user
has_many :chapters, dependent: :destroy
当我将通知定向给自己时,我得到了正确的通知,但是当我执行上述通知时,我得到了错误:
User(#58266780) expected, got #<ActiveRecord::Associations::CollectionProxy [#<User id: 3, name: "Otunba Olusaga of Saganation", username: "saga", email: "officialklashe@gmail.com", created_at: "2019-03-26 11:59:16", updated_at: "2019-03-27 09:13:58", admin: false, bio: "">]> which is an instance of User::ActiveRecord_Associations_CollectionProxy(#58325780)
更多研究表明,我必须“映射关注者(或使用批处理插入工具)以插入多个通知”,而我不知道该怎么做。
对此示例代码进行说明将非常有帮助,谢谢!
答案 0 :(得分:1)
我不确定您是否可以在这种情况下进行批量插入,因为我了解到,Notification gem需要每个通知都针对单个用户吗?也许这样做...
def create_notifications
self.user.followers.each do |follower|
Notification.create(notify_type: 'chapter', actor: self.book.user,
user: follower, target: self, second_target: self.book)
end
end