Currently I build a JSON object by doing:
@users = User.all @users.each do |user| @userlist << { :id => user.id, :fname => user.fname, :lname => user.lname, :photo => user.profile_pic.url(:small) } end
My challenge is I now want to include records from the @contacts
table that have a different set of fields than the User
model.
I tried doing
@users = User.all @contacts = current_user.contacts @users << @contacts
But that did not work. What's the best way to combine two similar models into one JSON object?
String message; JSONObject json = new JSONObject(); json. put("test1", "value1"); JSONObject jsonObj = new JSONObject(); jsonObj. put("id", 0); jsonObj. put("name", "testName"); json.
Creating Simple Objectsvar JSONObj = new Object(); Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '. ' Operator −
The structure of the JSON format was derived from the JavaScript object syntax. That's the only relationship between the JSON data format and JavaScript objects. JSON is a programming language-independent format. We can use the JSON data format in Python, Java, PHP, and many other programming languages.
json = User.all( :include => :contacts).to_json( :include => :contacts )
Sorry, let me give a more complete answer for what you're doing...
@users = User.all( :include => :contacts ) @userlist = @users.map do |u| { :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small), :contacts => u.contacts } end json = @userlist.to_json
Ok, so just forget me - I was having a bad day and totally missed the point of your question. You want some JSON that includes two unrelated sets of data. All the users, and the contacts just for the current user.
You want to create a new hash for that then, something like this...
@users = User.all @userlist = @users.map do |u| { :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small) } end json = { :users => @userlist, :contacts => current_user.contacts }.to_json
@userlist = @users.map do |u| u.attributes.merge!(:contacts=>current_user.contacts) end json = @userlist.to_json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With