ASP.NET MVC JsonResult and handlebars, no grip? - asp.net-mvc

I'm looking at example of using hadlebars.js, where template processing looks like:
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = { users: [
{username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" },
{username: "allison", firstName: "Allison", lastName: "House", email: "allison#test.com" },
{username: "ryan", firstName: "Ryan", lastName: "Carson", email: "ryan#test.com" }
]};
$("#content-placeholder").html(template(data));
and template is:
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
Now I have JSON result from ASP.NET MVC and I can't think the way I should descripbe my template, because it does not have "users" property, it looks like:
{[{username: "alan", firstName: "Alan", lastName: "Johnson", email: "alan#test.com" }]}
Can I somehow affect JsonResult to output what I need, or there is a way to fix template without touching the controller code?

In your controller replace:
return Json(users);
with:
return Json(new { users = users });

Alternatively, without introducing the anonymous object with the users property, you can change your template like so:
<tbody>
{{#each this}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>

Related

Merge Rails objects, only keep present values

I have an array of objects that I want to merge into one:
[
#<User firstname: 'John', middlename: '', lastname: nil>
#<User firstname: '', middlename: '', lastname: 'Doe'>
#<User firstname: nil, middlename: 'W.', lastname: nil>
]
This should become:
#<User firstname: 'John', middlename: 'W.', lastname: 'Doe'>
Is there an easy way for this or do I have to loop through all objects, look at the .attributes and build a new one?
Update: My current state of code
master = nil
my_array.each do |user|
if !master
master = user
else
user.attributes.each do |k, v|
if v.present? && !master.send(k).present?
master.send(:"#{k}=", v)
end
end
end
end
Well, it works, but the code doesn't look very clean...

Move one object in collection of objects in rails

Here is the scenario, I have these objects. Let's assume that this is a User:
The object came from:
#user = User.all
User Object
[<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]
How can I move one object up, for example I want to move User.id == 2? The result I want is shown below.
[<#User id: 2, firstname: "Paul", lastname: "Rich">,<#User id: 1, firstname: "John", lastname: "Pond">,<#User id: 3, firstname: "Jasmine", lastname: "Ong">]
I already got the answer. Here is what I made to made my question above worked.
#users = User.all
user_ids = User.pluck(:id)
user_ids.delete(2)
new_user_ids = [2]
user_ids.each do |id|
new_user_ids << id
end
#users.sort_by { |user| new_user_ids.index(user.id) }
And this made perfect!
We can also do it in a way like this:
Add a new method to Array. lib/rails_extensions.rb
class Array
def swap!(a, b = a - 1)
self[a], self[b] = self[b], self[a]
self
end
end
Then add this in config/environment.rb
require 'rails_extensions'
So we can use the method swap! for arrays and it will swap the object with the one before it. We can do something like this:
#users = User.all #[<#User id: 1>, <#User id: 2>]
user_id = #users.rindex {|user| user.id == 2}
#users = #users.swap!(user_id) #[<#User id: 2>, <#User id: 1>]
is this too ugly?
hash = [{ id: 1}, {id: 2}, {id: 3}]
hash.unshift(hash.delete(hash.select {|h| h[:id] == 2 }.first))
=> [{:id=>2}, {:id=>1}, {:id=>3}]

Ember-Data beta 3 and saving hasMany relationships and additonally one record with Rails

I am using Rails 4, Ember 1.2.0 and Ember Data 1.0.0-beta.3 and DS.ActiveModelSerializer.
I have trouble saving a new record with a 'has many' relationship. Two model records should be created but only by one POST request.
I have 2 models which looks like this:
Lingohub.SupportCase = DS.Model.extend({
subject: DS.attr('string'),
status: DS.attr('string'),
created_at: DS.attr('date'),
supportCaseMessages: DS.hasMany('supportCaseMessage')
});
Lingohub.SupportCaseMessage = DS.Model.extend({
supportCase: DS.belongsTo('supportCase'),
text: DS.attr('string'),
created_at: DS.attr('date')
});
My NEW route creates support case and support case massage:
Lingohub.SupportCasesNewRoute = Ember.Route.extend({
model: function() {
var support_case = this.store.createRecord('supportCase');
support_case.get('supportCaseMessages').createRecord();
return support_case;
}
});
My new form looks like this: (I don't know if you can bind an child attribute easier?)
<form {{action 'create' this on="submit"}} id="new_support_case">
{{input value=subject}}
{{!-- {{supportCaseMessages.0.text}} --}}
{{#each supportCaseMessages}}
{{textarea value=text}}
{{/each}}
<input type="submit">
</form>
'create' action in the controller:
Lingohub.SupportCasesNewController = Ember.ObjectController.extend({
actions: {
create: function(supportCase) {
var message = supportCase.get('supportCaseMessages.content')[0];
console.log(message.get('text'))
supportCase.save();
}
}
});
The POST Request to the Server only sends the 'support case'!!
{"support_case"=>{"subject"=>"aaaaaa", "status"=>nil, "created_at"=>nil}}
How can I send the additional record 'support case message' and the relationship ?
I try to answer my own question. If I do the following I get "support_case_messages" embedded in "support_case", is this really the best way to send 'two models' in one POST request?
Lingohub.SupportCaseSerializer = DS.ActiveModelSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key, jsonKey;
key = relationship.key;
jsonKey = Ember.String.underscore(key);
json[jsonKey] = [];
record.get(key).forEach(function(item) {
return json[jsonKey].push(item);
});
console.log(json)
return json;
}
});

How to get user fields in Ember js with has many associations

I have two models User and Recipe. I want to get user fields on recipe page and username in each recipe on user page. I don't know how to do it. In rails i have two has many association between User and Recipe. I added examples of my json arrays that I'm getting from rails.
My json user array
user: {
id: 1,
name: "ejiqpep",
email: "ejiqpep#gmail.com",
recipe_ids: [
1,
2
],
box_recipe_ids: [
1,
2
]
}
My json recipe array
recipe: {
id: 1,
title: "recipe01",
about: "about01",
ingredients: "ingredients01",
steps: "steps01",
visibility_type: true,
slug: "recipe01",
user: {
id: 1,
name: "ejiqpep",
email: "ejiqpep#gmail.com",
recipe_ids: [
1,
2
],
box_recipe_ids: [
1,
2
]
}
}
user.js.coffee
App.User = DS.Model.extend
name: DS.attr('string')
email: DS.attr('string')
recipes: DS.hasMany('App.Recipe')
box_recipes: DS.hasMany('App.Recipe')
recipe.js.coffee
App.Recipe = DS.Model.extend
user: DS.belongsTo('App.User')
title: DS.attr('string')
user.handlebars (I want to get user name in each recipe)
<h1>{{name}}</h1>
<p><b>Email:</b> {{email}}</p>
<h3>User recipes</h3>
{{#each recipe in recipes}}
<div>
<span>{{recipe.id}}</span>
<span>!!!I want to show username here!!!</span>
<span>{{#linkTo recipe recipe}} {{recipe.title}} {{/linkTo}}</span>
</div>
{{/each}}
<h3>User box_recipes</h3>
{{#each fav in box_recipes}}
<div>
<span>{{fav.id}}</span>
<span>!!!I want to show username here!!!</span>
<span>{{#linkTo recipe fav}} {{fav.title}} {{/linkTo}}</span>
</div>
{{/each}}
recipe.handlebars
<h1>{{title}}</h1>
<p>User {{user.name}}</p> # I want to show username here!!!
i donĀ“t know exactly if it works ... but give it a try :
update:
{{#each recipes}}
<div>
<span>{{id}}</span>
<span>{{../name}}!!!I want to show username here!!!</span>
<span>{{#linkTo recipe this}} {{title}} {{/linkTo}}</span>
</div>
{{/each}}

In my Rails app, JSON formatted results are appearing in a HTML view response

In a Rails 3.1 app, I have a controller returning a set of objects (children) in an index view using this code:
def index
#children = Child.all
#base_class = "children-index"
#title = "Your Children"
respond_to do |format|
format.html # children/index.html.erb
format.json { render :json => #children }
end
end
The index.html.erb view is written like so:
<h1><%= title %></h1>
<ul>
<%= #children.each do |child| %>
<li><%= link_to child.fullname, child_path(child) %></li>
<% end %>
</ul>
For some reason, the JSON response is getting thrown into the HTML response and I cannot determine the reason. None of my other index views are having this issue and their code is very close to the same.
John Jake Smith Jr
Jane Ann Doe
[#<Child id: 1, firstname: "John", middlename: "Jake", lastname: "Smith", suffix: "Jr", gender: "Male", dob_actual: "2011-01-05", dob_expected: "2011-01-01", height: 30, weight: 40, created_at: "2011-10-28 21:32:54", updated_at: "2011-10-28 21:32:54">, #<Child id: 2, firstname: "Jane", middlename: "Ann", lastname: "Doe", suffix: "", gender: "Female", dob_actual: "2011-05-05", dob_expected: "2011-05-01", height: 30, weight: 12, created_at: "2011-11-07 18:08:54", updated_at: "2011-11-07 18:08:54">]
That's not JSON, that's inspect output. You're getting that because each returns #children and you're using <%= here:
<%= #children.each do |child| %>
You want just this:
<% #children.each do |child| %>
Did you forget to do #children.to_json in your controller?

Resources