使用一对多关联为公共活动Rails gem

时间:2015-04-01 18:18:35

标签: ruby-on-rails ruby activerecord associations public-activity

我刚刚开始使用PublicActivity gem并希望在整个网站上显示作者的活动。在应用中,作者有许多图书。当作者发布新书时,我希望在用户的Feed中显示通知。我尽力翻译代码example中显示的内容,这是我到目前为止所提出的内容:

模型

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_idrecipient_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">

1 个答案:

答案 0 :(得分:1)

要保存作者,最好在创建新书时使用该关系

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

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

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

注意:
预填充对象的原因是当您在活动记录关系对象上调用new时,条件内的所有条件都用于创建新对象,例如

Book.where(author: some_author).new

这会生成一个图书实例,而author_id将是where查询中some_author的ID。

因此,当我们执行author.books时,这会创建一个查询

Book.where(author_id: author.id)

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

<强> PS: 这也适用于where

中的多个参数
Model.where(key1: value1, key2: value2, key3: value3).new

将创建一个新实例,其中已填充属性key1key2key3