Binding to relationship property - binding

I'm trying to bind an attribute of a DS.belongsTo relationship like this:
App.User = DS.Model.extend({
name: DS.attr('string')
});
App.Post = DS.Model.extend({
text: DS.attr('string'),
user: DS.belongsTo('App.User'),
userNameBinding: 'user.name'
});
I know this example is a little bit stupid, but the idea is here.
Unfortunately, it does not work (in model.js, at this line):
Uncaught TypeError: Cannot call method 'send' of null
I also tried to use Ember.Binding.oneWay, but it does not work either. My current workaround is pretty ugly:
App.Post = DS.Model.extend({
// code omitted
userName: function() {
return this.get('user.name');
}.property('user.name')
});
You can test it in this JSFiddle.
Ember version used:
ember-data on master
ember v1.0.0-pre.2-311-g668783a

There appears to be a bug with bindings to properties that rely on state set up in init. I have filed a bug on the Ember issue tracker.
For a less ugly solution, you can use Ember.computed.alias:
App.Post = DS.Model.extend({
text: DS.attr('string'),
user: DS.belongsTo('App.User'),
userName: Ember.computed.alias('user.name')
});
I have a working example in this JSBin.

Related

Ember - ember.debug.js:19746 Error: Failed to create an instance of 'adapter:application'

I am building an ember app and am attempting to connect to a rails API, to read in data from a questions end point.
These are two separate applications.
My Code is as follows:
adapters/application.js
import DS from 'ember-data';
import ActiveModelAdapter from 'active-model-adapter';
export default DS.ActiveModelAdapter.extend({
host: 'http://localhost:3000/api/v2'
});
models/questions.js
import DS from 'ember-data';
export default DS.Model.extend({
text: DS.attr('string'),
title: DS.attr('string'),
debateTopicId: DS.attr('string'),
releaseAt: DS.attr('date'),
expiresAt: DS.attr('date')
});
routes/questions.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('question');
}
});
templates/questions.hbs
<h2>This is the Questions Feed</h2>
{{#each model as |question|}}
<h3>{{question.id}} - {{question.text}}</h3>
{{/each}}
The end point I am attempting to call to is:
http://localhost:3000/api/v2/questions
I get the error:
ember.debug.js:19746 Error: Failed to create an instance of 'adapter:application'. Most likely an improperly defined class or an invalid module export.
at instantiate (ember.debug.js:1477)
at lookup (ember.debug.js:1336)
at Object.lookup (ember.debug.js:1255)
at Class.lookup (ember.debug.js:34526)
at ContainerInstanceCache.instanceFor (container-instance-cache.js:62)
at ContainerInstanceCache._findInstance (container-instance-cache.js:51)
at ContainerInstanceCache.get (container-instance-cache.js:39)
at Class.retrieveManagedInstance (store.js:2105)
at Class.lookupAdapter (store.js:2111)
at Class.adapterFor (store.js:2051)
Any ideas what the issue is?

Cannot get Rails REST API to work with Ember.js

I'm busy following this Ember.js tutorial, but I'm trying to implement it using the Ember 2.0 way of doing things (modules, using Ember CLI and the ember-cli-rails gem). It's rather difficult since none of the Ember guides follow these conventions.
As per the tutorial, I'm using Rails as a JSON API and it looks like everything works like it should in terms of serving the proper JSON responses. Problem is, I can't get my leads model to work.
I'm getting a TypeError: Cannot read property 'typeKey' of undefined error from ember.debug.js. I'm also getting a undefined is not a function error from ember.adapter.js
My project looks as follows:
app/store.js
import DS from 'ember-data';
export default DS.RESTAdapter.reopen({
url: 'https://localhost:3000',
namespace: 'api/1'
});
app/router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.resource('leads', { path: '/' });
});
export default Router;
app/adapters/application.js
import DS from "ember-data";
var ApplicationAdapter = DS.ActiveModelAdapter.extend({
host: 'http://localhost:3000',
namespace: 'api/v1'
});
export default ApplicationAdapter;
app/models/lead.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
email: DS.attr('string'),
phone: DS.attr('string'),
status: DS.attr('string', { defaultValue: 'new' }),
notes: DS.attr('string'),
});
app/routes/leads.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() { return this.store.find('lead') }
});
I don't see any HTTP requests being made to Rails, so I assume that it breaks even before trying to use the API. Can anybody please point out what I'm doing wrong here?
Looks like the issue was store.js, which shouldn't be used here. Not sure why, but removing it causes everything to work as it should.
UPDATE: So, upon learning more of how Ember works, I now know the issue was not the file, but that Rails returns the wrong type of json back. The Ember REST adapter expects json keys to use an underscore, eg. first_name, while Rails returns it in camel case, eg. firstName.
To use Ember with Rails, you need to use the ActiveModel adapter. The newest version of ActiveModelSerialisers(AMS) supports JSON API.

Using w2ui with Rails: Submitting a form

I am trying to build a Rails application with w2ui.
I have hit my first snag when trying to submit a form built with w2ui.
I have a simple model called Project with two attributes: name and description.
The standard, scaffolded form built by Rails submits the form data as follows:
project[name]:Test Project
project[description]:A description
However, the form data submitted by w2ui looks as follows:
record[project[name]]:Test Project
record[project[description]]:A description
That is, w2ui wraps the data further in a record variable, which means I must either change the controller in Rails, which I am not wanting to do, or find a way to get w2ui to not wrap the data the way it does.
My code for w2ui is taken pretty much straight from their demos:
$(function () {
$('#project_form').w2form({
name : 'project_form',
url : '/projects.json',
fields: [
{ name: 'project[name]', type: 'text', required: true },
{ name: 'project[description]', type: 'text' }
],
actions: {
reset: function () {
this.clear();
},
save: function () {
this.submit(); // tried .save() as well, same result
}
}
});
});
First prize would be if w2ui could be configured to do this. Any ideas? I don't see anything in the w2ui docs...
I faced the same problem and straight away could not get a solution.
I added the below to form options, it just copies all params inside record to post data.
onSubmit: function(formName, formObj){
$.extend(formObj.postData, formObj.postData.record);
},
Its been long you have asked this question, if you knew a better solution please let me know.

Put_connections to create a new event with Koala?

I'm trying to create a new event using the Koala gem and it's returning with the same error I got when I tried to update an event with an incorrectly formatted datetime value.
I can update just fine now but still cannot create an event.
Here's the code I use on my update method which works:
start_time = safe_params[:start_time].in_time_zone
end_time = safe_params[:end_time].in_time_zone
graph.put_connections(safe_params[:fb_id], "event", {
name: safe_params[:name],
description: safe_params[:description],
privacy: safe_params[:privacy]
})
And here's the code I'm trying to use to create a new event object:
graph.put_connections("/me/events", "event", { #this is the line that errors
name: safe_params[:name],
description: safe_params[:description],
privacy: safe_params[:privacy]
})
According to Facebook's documentation on creating an event (https://developers.facebook.com/docs/graph-api/reference/user/events/), I should be able to create a new event just by initiating a post to /me/events. Anyone have any idea?
I also tried:
graph.put_connections("/"+current_user.fb_id.to_s+"/events", "event", {
Thanks!
What happens if you do something like this?
graph.put_connections("me", "events", {
name: safe_params[:name],
description: safe_params[:description],
privacy: safe_params[:privacy],
start_time: ...,
end_time: ...
})
So after messing with Facebook's Graph Explorer and attempting hundreds of different combinations with put_connections I decided to make a straight graph_call using Koala.
Finally got an ID response back. I almost cried. Thought I'd share with the community in case there's someone else trying to do the same thing.
event_response = graph.graph_call("/me/events",{
name:safe_params[:name],
start_time: safe_params[:start_time],
privacy_type: safe_params[:privacy],
access_token: current_user.oauth_token}, "POST")
safe_params[:fb_id] << event_response["id"]
#event = Event.create safe_params
I make the call in a stored variable event_response because the Facebook Id returned is used in my app.
First thing I found out: despite using "privacy" as the name of the privacy field when GETting from Facebook and saying so in their documentation, "privacy_type" is actually what you want (found this out in another SO post).
The second thing I found out is even though you are authenticated (have a user token) when you make a graph_call you STILL need to pass along the current_user access token along with making a POST graph_call.
Hope this helps someone!

Delete an instance of class using mechanize in rails

I am using mechanize to deal with a form . I have parsed the form using mechanize and the output comes is as follows:
{forms
#<Mechanize::Form
{name nil}
{method "POST"}
{action "/dashboard/checks/50114dbeae6f61b428000ad8"}
{fields
[hidden:0x60c476a type: hidden name: _method value: put]
[text:0x60c4616 type: text name: check[name] value: Testing]
[text:0x60c4512 type: text name: check[url] value: http://www.pintile.com]
[text:0x60c445e type: text name: check[interval] value: 120]
[text:0x60c435a type: text name: check[maxTime] value: 1500]
[textarea:0x60c4116 type: name: check[tags] value: ]}
{radiobuttons}
{checkboxes}
{file_uploads}
{buttons
[button:0x60c3d88 type: submit name: value: ]
[button:0x60c3d24 type: submit name: delete value: ]
There are 2 buttons in this form
Save Changes(1st), Delete(2nd),
I use the following code to save the changes and it works fine:
form.field_with(:name => "check[name]").value = "Testing"
button = form.buttons.first
agent.submit(form, button)
The changes are saved successfully. But when i try to delete using the code below it does not work:
button = form.buttons.first
agent.submit(form, button)
It does nothing. Please help me out to get over with this issue.
If the website is a typical rails form, the delete button is most likely a JavaScript action. Mechanize does not support JavaScript. You may want to use something like capybara with the web kit driver instead, which has full JavaScript support and all of the functionality you already have in mechanize.
The code snippet below work well with link.Have you tried click
agent.get("http://your url")
agent.page.link_with(:text => "link name").click
Give it a try..
Else as mentioned above you can use Capybara
Delete is the last button. Therefore you want:
button = form.buttons.last
agent.submit(form, button)
or more simply:
form.submit form.buttons.last
If Mechanize is good enough for you and you do not require any javascript support that would bring Capybara, you should be able to emulate what the Javascript does. In this case, the source would be needed to better know what append, but I guess the value of the hidden field _method is replaced by delete prior the submit.

Resources