0

我刚开始使用PublicActivity gem,想在整个站点中显示作者的活动。在应用程序中,作者有很多当作者发布新书时,我希望在用户的提要中出现通知。尽我最大的努力翻译代码示例中显示的内容,这是我到目前为止的想法:

楷模

class Reader < ActiveRecord::Base
end

class Author < ActiveRecord::Base
    has_many :books
end

class Book < ActiveRecord::Base
  include PublicActivity::Model
  tracked owner: :author, recipient: :reader

  belongs_to :author, :class_name => "Author"
  belongs_to :reader, :class_name => "User"
end

活动控制器

class ActivitiesController < ApplicationController
  def index
    @activities = PublicActivity::Activity.all
  end
end

活动索引视图

<% @activities.each do |activity| %>
    <%= activity.inspect %> # Using inspect for now to debug
<% end %>

现在在控制台中,我正在创建书籍并将其附加到作者(author作为实例变量),如下所示:

author.books << Book.create(name: "Jaws")

活动正在被记录,但实际上所有者应该是作者而接收者应该是用户时,owner_idand是 nil。recipient_id

#<PublicActivity::Activity id: 1, trackable_id: 1, trackable_type: "Book", owner_id: nil, owner_type: nil, key: "book.create", parameters: {}, recipient_id: nil, recipient_type: nil, created_at: "2015-04-01 17:36:18", updated_at: "2015-04-01 17:36:18">
4

1 回答 1

1

为了保存作者,您最好在创建新书时使用关系

author.books.create(name: "Jaws")

然后,如果您想保存阅读器,则需要将其添加到 args 哈希中

author.books.create(name: "Jaws", reader: some_user)

注意:
之所以这样预填充对象,是因为当你在一个活动的记录关系对象上调用new时,条件里面的所有条件都是用来创建新对象的,例如

Book.where(author: some_author).new

这将生成 book 的实例,并且author_id将是some_authorfrom where 查询的 id。

所以当我们这样做时,author.books这创建了一个查询

Book.where(author_id: author.id)

通过调用 new,新书将具有作者的 id。

PS: 这也适用于where

Model.where(key1: value1, key2: value2, key3: value3).new

将创建一个新实例,其中属性key1, key2,key3已被填充。

于 2015-04-01T20:38:41.133 回答