是否可以通过ID显示数据?

时间:2015-12-29 13:35:45

标签: angularjs

我为抽象标题道歉。我正在#163 Self-Referential Association之后在我的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

添加朋友后,它会在表格中创建一条新记录,其中包含用户ID和朋友ID。

{"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"}

friendships_controller.rb我有,

def index
  friend = current_user.friendships
  render :json => friend.to_json()
end

因此,我可以看到friend_iduser_id的关联。但如果我想在ng-repeat中显示朋友,我将需要更多数据。

friend_id是添加的用户ID。因此,如果用户将第4个用户添加到他的朋友列表中,则friend_id将为4.因此可以将friend_id连接到user_id,以便我可以显示{{ user.name }}或我需要将名称,生日等所有数据添加到朋友创建函数的参数?

例如,我会将朋友名称添加到参数中,以便JSON看起来像这样,

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

然后我可以执行ng-repeat friend in friendships {{ friend.name }}

之类的操作

0 个答案:

没有答案