Ember.js Query Parameters - Update query results when creating a model - ruby-on-rails

I am using the new query-params in Ember.js to filter entries by date. I have added a field to add new entries, with the date being automatically assigned as the query date. When a new entry is added it only shows up on the page when I refresh. Is there any way to retrigger the query without changing the query itself?
Controller: (simplified)
queryParams: 'date'
date: null
filteredEntries: ( ->
date = #get('date')
model = #get('model')
if (date)
return entries.filterProperty('date', date)
else
return entries
).property('date', 'model')
actions:
createEntry: ->
entry = #store.createRecord('entry', { date: #get('date') })
entry.save()
I also tried this, but it didn't work:
entry.save().then -> this.transitionTo({queryParams: { date: #get('date')}})

I think this is what you are looking for (in your route):
App.MyRoute = Ember.Route.extend({
queryParams: {
date: {
refreshModel: true
}
},
});
This will refresh your model everytime the value of date changes.

Related

SDN5/OGM3 compare java.util.Date at Cypher query

I have the following entity:
#NodeEntity
public class Action {
...
#Index(unique = false)
private Date createDate;
...
}
I need to get the last Action that was created during some previous period of time.
In order to do this I have implemented the following repository method:
#Repository
public interface ActionRepository {
#Query("MATCH (a:Action)-[:CREATED_BY]->(u:User) WHERE a.entityType = {entityType} AND a.createDate <= {minCreateDate} AND u.id = {userId} RETURN a ORDER BY a.createDate DESC LIMIT 1")
Action findLastByEntityTypeForUser(#Param("entityType") String entityType, #Param("minCreateDate") Date minCreateDate, #Param("userId") Long userId);
}
I use the following code to test this method:
decisionDao.create("Decision2", "Decision2 description", null, false, null, user1);
Date minStartDate = DateUtils.addMilliseconds(new Date(), -1000 * 60);
Action user1LastAction = actionRepository.findLastByEntityTypeForUser(Decision.class.getSimpleName(), minStartDate, user1.getId());
assertNotNull(user1LastAction); // test fails here because of NPE
but without this part of the Cypher query AND a.createDate <= {minCreateDate} I can successfully find Action instance.
At Neo4j level my data looks like:
{
"updateDate":"2017-10-08T12:21:39.15
3Z",
"entityName":"General",
"en
tityType":"CriterionGroup",
"entityId":1,
"id":1,
"type":"CREATE",
"createDate":"2017-10-08T12:21:39.153Z"
}
What am I doing wrong and how to properly compare the dates with SDN/OGM and Cypher?
Also, is there any way to tell SDN/OGM to store java.util.Date object as long milliseconds and as String?
the minCreateDate parameter you use for your find-Method is of type Date and the createDate property is a String. So, this part a.createDate <= {minCreateDate} is basically comparing the String representation of minCreateDate and the String property createDate.
In my projects, I usually save the dates and timestamps as long both in the database and in my code.
Or even better, if the date attributes are crucial for my application, I'm using the "Time Tree Model" approach: https://graphaware.com/neo4j/2014/08/20/graphaware-neo4j-timetree.html

Ember date belongTo with serialized id

App.Locale = DS.Model.extend
language: DS.belongsTo("language")
App.LocaleSerializer = App.ApplicationSerializer.extend
attrs:
language: { serialize: "id", deserialize: "records" }
Using ember with rails as the backend. I am trying to create a locale, which has a dropdown to select a language. My idea is to pass a language_id to the backend, however I get the following when I submit.
{"locale"=>{"language"=>"15" }
How do I convert this to look like
{"locale"=>{"language_id"=>"15" }
Thanks
Assuming that you're using the ActiveModelSerializer, I think your answer is here. Just add the key attribute to the hash:
App.LocaleSerializer = App.ApplicationSerializer.extend
attrs:
language: { key: "language_id", serialize: "id", deserialize: "records" }
If you only want to use language_id when serializing, but get language when deserializing, you can always override serializeBelongsTo:
App.LocaleSerializer = App.ApplicationSerializer.extend
serializeBelongsTo: (record, json, relationship) ->
if relationship.key is 'language'
json.language_id = Ember.get record, 'language.id'
else
#_super record, json, relationship

Jquery Datepicker with MVC - Get date picked

I have the following in my MVC View:
#Html.TextBoxFor(model => model.FromDateCollected, new { style = "width:90px;" })
In query I have the following:
$("#FromDateCollected").datepicker();
To get the selected date, I tried the following:
var dt = $("#FromDateCollected").datepicker("getDate")
alert(dt);
but getting:
[object Object]
just get the value of text box
var dt = $("#FromDateCollected").val();
alert(dt);
If you want to get the selected date, when user select a date in the calendar, you can do that on the onSelect event
$(function() {
$('#FromDateCollected').datepicker({
onSelect: function(dateText, inst) {
alert(dateText);
}
});
});
Working sample http://jsfiddle.net/pDmjm/5/
EDIT : as per the comment,
$("#FromDateCollected").datepicker("getDate") will give you a Date object and $("#FromDateCollected").val(); will give you a string with current value in the textbox. write the result to a console and you will see the result.
Sample : http://jsfiddle.net/pDmjm/14/ (check firebug console after alerts)
You can get the date from the textbox value.
var dt = new Date(Date.Parse($('#FromDateCollected').val()));
alert(dt);

MVC 3 WebGrid with a dynamic source

I have a dynamic list of data with a dynamic number of columns being created by a PIVOT function. Everything more or less works, but I wanted to apply some custom formatting to some of the columns. I figured out how to get a list of the columns by just taking the first row and casting it like so:
var columns = Model.Comparisons.Select(x => x).FirstOrDefault() as IDictionary<string, object>;
Next I decided to create my List by looping over the "columns", which works as long as I reference the dynamic fields in the "format:" clause by their dynamic field name directly for example:
foreach (var c in columns)
{
switch (c.Key)
{
case "Cost":
cols.Add(grid.Column(
columnName: c.Key,
header: c.Key,
format: (item) => Convert.ToDecimal(item.Cost).ToString("C")));
break;
default:
cols.Add(grid.Column(columnName: c.Key, header: c.Key, format: item => item[c.Key]));
break;
}
}
The "default" does not dynamically get the value of each record. I believe it has to do with the "item[c.Key]" vs item.Cost. The problem is I don't want to have to write different case for each field, primarily because I don't know them ahead of time as the data can change. There are about 6 fields that will always be present. I do know however the datatype, which is why I wanted to put a custom format on them.
EDIT
I managed to solve this by writing an extension method.
public static class DynamicDataHelper
{
public static WebGridColumn GetColumn(this HtmlHelper helper, string vendor)
{
return new WebGridColumn()
{
ColumnName = vendor,
Header = vendor,
Format = (item) => helper.ActionLink(
(string)Convert.ToDecimal(item[vendor]).ToString("C"),
"VendorSearch",
"Compare",
new { Vendor = vendor, mpn = item.MPN },
new { target = "_blank" })
};
}
}
I edited my post with the Html Helper that I wrote that will in effect build the custom WebGridColumn objects I was having problems with. The "vendor" is passed in from the View and is then resolved at runtime. It works great.

How Do I Combine Two Query Results In To A Map, In Grails?

I'm new to Grails development.
I have a domain class like this :
class DaySchedule {
Date Todaysdate
String startTime;
String endTime;
String task
int priority
boolean completed
static belongsTo = [ schedule : Schedule ]
}
I have bootstrapped with some test data's. Now I want to do a query, with following condition :
I need to pick each task (which are stored in bootstrap.groovy) which are belongs to a particularTodaysdate.
For example if I have these statements in my BootStrap.groovy :
//other codes
def daySchedule3 = new DaySchedule(Todaysdate:new Date(),
startTime:"6pm",endTime:"10pm",
task:"ReaD git...",completed:false)
def daySchedule4 = new DaySchedule(Todaysdate:new Date()+1,
startTime:"10am",endTime:"12pm",
task:"Read MySQL....",completed:false)
Now clearly the task, ReaD git... belongs to a day (which is today as I have passed new Date() into it).
To find these I came up with a partial solution like this:
def allTasks = DaySchedule.findAllByTaskIsNotNull()
def dates = allTasks.collect { it.Todaysdate }
def tasks = dates.collect {
def queryParameter = new DaySchedule(Todaysdate:it)
def todaysWork = DaySchedule.findAll(queryParameter)
todaysWork.task
}
I have a problem with this code. I couldn't use collectEntries method on the dates and tasks so that I convert it into map of a particular date(i.e dates) with values as tasks. (which is what I tried for!)
Now I'm left lone. I couldn't not able to find a way to guess for which dates the tasks belongs to.
Any other solutions for it?
Thanks in advance.
It sounds like you're trying to get a map with a key of the date, and a value of the task name, for all of the domain objects DaySchedule. You may want to try Collection.groupBy. For example:
def allTasks = DaySchedule.findAllByTaskIsNotNull()
def tasksByDate = [:] // start with empty map
tasksByDate.putAll(
allTasks.groupBy { task ->
// group by just the date portion, ignoring time
// clone since clearTime modifies original
task.todaysDate.clone().clearTime()
}.collect { date, daySchedule ->
// change from map of date -> daySchedule to map of date -> task
[date, daySchedule.task] as MapEntry
}
)
I think you have a design problem somewhere... it would be easier to have something like :
class Task {
Date startTime;
Date endTime;
String description
int priority
boolean completed
static belongsTo = [ schedule : Schedule ]
String toString() {
return "${description} : from ${startTime} to ${endTime}"
}
}
Then, you can list all the dates for which you have tasks in them like this :
java.text.DateFormat df = java.text.DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
def days = Task.list().collect {
df.format(it.startTime);
}.unique()
So now the "days" variable contains an array of strings of unique days present in your database with tasks associated.
If you want to list the tasks by day, you can then do :
days.each { dayString ->
def date = df.parse(dayString)
def dayTasks = Task.findAllByStartTimeBetween(date, date+1)
println "Tasks for ${dayString}"
dayTasks.each {
println " - ${it}"
}
}

Resources