在不同的控制器中包含用户数据

时间:2015-12-30 16:49:00

标签: ruby-on-rails json

我正在尝试以json的形式呈现活动列表,以便我可以在我的AngularJS应用程序中使用该数据。这是我的活动控制器:

def index
  @activities = PublicActivity::Activity.order("created_at desc")
  respond_to do |format|
    format.json do
      render :json => @activities.to_json()
    end
  end
end

它像这样渲染json:

{"id":3,"trackable_id":6,"trackable_type":"Movie","owner_id":1,"owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T12:31:24.765Z","updated_at":"2015-12-30T12:31:24.765Z"},
{"id":2,"trackable_id":5,"trackable_type":"Movie","owner_id":1,"owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T11:55:06.766Z","updated_at":"2015-12-30T11:55:06.766Z"},

如您所见,有一个名为owner_id的值。这与执行活动的用户的user id一致。

我当然有一个名称,电子邮件等值的用户模型。因此,对于id为1的第一个用户,它看起来像这样,

{"id":1,"email":"john@doe.nl","name":"John Doe"},

是否可以检查活动中的owner_id并找到重合的user_id,然后将名称,电子邮件等值添加到活动控制器中?

结果将是这样的json渲染:

{"id":3,"trackable_id":6,"trackable_type":"Movie","owner_id":1,"email":"john@doe.nl","name":"John Doe","owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T12:31:24.765Z","updated_at":"2015-12-30T12:31:24.765Z"},
{"id":2,"trackable_id":5,"trackable_type":"Movie","owner_id":1,"email":"john@doe.nl","name":"John Doe","owner_type":"User","key":"movie.create","parameters":{},"recipient_id":null,"recipient_type":null,"created_at":"2015-12-30T11:55:06.766Z","updated_at":"2015-12-30T11:55:06.766Z"},

2 个答案:

答案 0 :(得分:1)

当然!只需将其包含在to_json方法中:

render :json => @activities.to_json(include: :owner)

假设activity has_one owner

您还可以选择仅包含所包含模型中的特定属性。有关如何处理这些序列化的更多信息,请参阅to_json Rails Docs

答案 1 :(得分:0)

您可以使用active_model_serializers gem,然后为您的用户和活动创建序列化程序:

# app/serializers/user_serializer.rb
class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name ...
end

# app/serializers/activity_serializer.rb
class AuthorSerializer < ActiveModel::Serializer
  # some attributes
  has_one :user
end