将用户数据注入json输出

时间:2015-12-29 14:46:50

标签: ruby-on-rails

我在我的Rails / Angular应用程序中构建了一个友谊功能,目前我可以在用户之间创建关系,但我仍然遇到了一个小问题。

我有一个friendships表,

create_table "friendships", force: :cascade do |t|
  t.integer  "user_id"
  t.integer  "friend_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

当用户将其他用户添加为朋友时,会创建新记录

这是friendships_controller

上的索引定义
def index
  friend = current_user.friendships
  render :json => friend.to_json()
end

这是json输出。

{"id":1,"user_id":1,"friend_id":2,"created_at":"2015-12-29T13:18:44.499Z","updated_at":"2015-12-29T13:18:44.499Z"},
{"id":2,"user_id":1,"friend_id":3,"created_at":"2015-12-29T13:18:45.463Z","updated_at":"2015-12-29T13:18:45.463Z"},
{"id":3,"user_id":1,"friend_id":4,"created_at":"2015-12-29T13:18:46.420Z","updated_at":"2015-12-29T13:18:46.420Z"}

但这些数据几乎无法使用。是否可以在友谊json中注入用户数据?

{"id":1,"email":"peter@peter.nl","name":"Peter Boomsma"},
{"id":2,"email":"jan@jan.nl","name":"Jan Jansen"},
{"id":3,"email":"kees@kees.nl","name":"Kees Keesen"},
{"id":4,"email":"piet@piet.nl","name":"Piet Pietersen"}

所以友谊json输出看起来像这样,

{"id":1,"user_id":1,"friend_id":2,"email":"jan@jan.nl","name":"Jan Jansen","created_at":"2015-12-29T13:18:44.499Z","updated_at":"2015-12-29T13:18:44.499Z"},
{"id":2,"user_id":1,"friend_id":3,"email":"kees@kees.nl","name":"Kees Keesen","created_at":"2015-12-29T13:18:45.463Z","updated_at":"2015-12-29T13:18:45.463Z"},
{"id":3,"user_id":1,"friend_id":4,"email":"piet@piet.nl","name":"Piet Pietersen","created_at":"2015-12-29T13:18:46.420Z","updated_at":"2015-12-29T13:18:46.420Z"}

*删除功能*

app.factory('removeFriend', ['$http', function($http) {
  return {
    removeFriend: function(friend) {
    var _friendID =  parseInt(friend.id);
    console.log (_friendID)
    return $http.delete('/friendships/'+_friendID + '.json');
    }
  };
}])

这是angular中的删除服务,这里传递的是friend.id而不是friendship.id。

1 个答案:

答案 0 :(得分:1)

我将实现以下内容:

在用户模型中添加关联以获取用户的朋友,即用户对象

has_many :friends, through: :friendships, foreign_key: 'friend_id'

现在在控制器中获取朋友数据

friends = current_user.friends.as_json(:only => [:name, :email, :id])
render :json => friends # [{:name => 'test', :email => 'test@test.com', :id => 1},{...}]

如果您需要响应中的当前用户数据,您可以执行以下操作:

render :json => current_user.as_json(only: [:id, :name, :email]).merge(:friends => friends)
# {:id => 1, :name => 'user', :email => 'testuser@test.com', friends: [{:name => 'test', :email => 'test@test.com', :id => 1},{}]}

在上述回复中,您可以发送所需的确切数据而无需重复。