New to Ruby on Rails 4.0 and I am having some trouble getting my JSON to add the data from my joined table. I am using AngularJS on the front end, and I can't seem to find a good example on here to help me out.
In short, I have a Invite with a User ID. I have a User with a User ID. Knowing the Invite ID, I want to get the name of the User that corresponds to that invite.
Invite 1: UserID: 10
Invite 2: UserID: 11
Invite 3: UserID: 12
UserID: 10 Name: Owen
UserID: 11 Name Greg
Controller - Invites
# GET /invites/1
# GET /invites/1.json
def show
@invite = Invite.includes(:user).find(params[:id]).to_json(include: :user)
end
Model - Invite
class Invite < ActiveRecord::Base
belongs_to :user
has_one :meal
has_one :event
has_one :registry
end
Model - User
class User < ActiveRecord::Base
has_one :invite
end
However I only get this whenever I check the /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}
Any help here is much appreciated!
Your show should be:
def show
@invite = Invite.includes(:user).find(params[:id])
respond_to do |format|
format.json { render :json => @invite.to_json(include: :user) }
end
end
I recommend you to use JBuilder http://rubygems.org/gems/jbuilder . You can use @invite.to_json, but JBuilder gives you much more control on the output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.