gpt4 book ai didi

ruby-on-rails - Ruby on Rails - 连接两个表将结果添加到 JSON

转载 作者:数据小太阳 更新时间:2023-10-29 08:27:31 24 4
gpt4 key购买 nike

Ruby on Rails 4.0 的新手,我在获取我的 JSON 以添加我连接表中的数据时遇到了一些问题。我在前端使用 AngularJS,我似乎无法在这里找到一个好的例子来帮助我。

简而言之,我有一个带有用户 ID 的邀请。我有一个具有用户 ID 的用户。知道邀请 ID,我想获取与该邀请对应的用户名。

Invite 1: UserID: 10
Invite 2: UserID: 11
Invite 3: UserID: 12

UserID: 10 Name: Owen
UserID: 11 Name Greg

Controller - 邀请

# GET /invites/1
# GET /invites/1.json
def show
@invite = Invite.includes(:user).find(params[:id]).to_json(include: :user)
end

模型 - 邀请

class Invite < ActiveRecord::Base
belongs_to :user
has_one :meal
has_one :event
has_one :registry
end

模型 - 用户

class User < ActiveRecord::Base
has_one :invite
end

然而,我只有在检查/invites/1 时才会得到这个。

{"id":1,"created_at":"2013-12-06T20:14:39.001Z","updated_at":"2013-12-06T20:58:15.597Z","event_id":7,"meal_id":8,"registry_id":0,"rsvp":false,"user_id":9}

非常感谢这里的任何帮助!

最佳答案

你的节目应该是:

def show
@invite = Invite.includes(:user).find(params[:id])
respond_to do |format|
format.json { render :json => @invite.to_json(include: :user) }
end
end

关于ruby-on-rails - Ruby on Rails - 连接两个表将结果添加到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com