Reputation: 190
I have quiz fixtures that have a property called questions, which is an array of ids of associated questions. I want to create a computed property on the model called firstQ that returns the first id in the questions array. Ultimately I would like to take that id and use it to link to a question route I have created.
I can not figure out though, how to access that first id in the questions array. Is this even the best way to approach this? Please help.
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Quiz = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
questions: DS.hasMany('question', {async: true}),
firstQ: function() {
return this.get('questions')//where to go next?, on right track?;
}.property()
});
App.Question = DS.Model.extend({
question: DS.attr('string'),
quiz: DS.belongsTo('quiz', {async: true}),
answers: DS.attr('string')
});
//fixtures
App.Quiz.FIXTURES = [
{
id: 1,
name: 'The JavaScript Quiz',
description: 'take this quiz and find out if you\'re a super genious',
questions: [100,101]
}
];
App.Question.FIXTURES = [
{
id:100,
question: 'Inside which HTML element do we put the JavaScript',
quiz: 1,
answers: [
{ answer: 'alpha', weight: 0 },
{ answer: 'beta', weight: 5 }
]
}
]
Upvotes: 0
Views: 727
Reputation: 190
Okay, so I figured out how to to do this via the computed property on the model. Here's the updated code for the App.Quiz model:
App.Quiz = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
questions: DS.hasMany('question', {async: true}),
firstQuestion: function() {
return this.get('questions.firstObject');
}.property('questions.firstObject')
});
Upvotes: 1
Reputation: 782
You can use the firstObject property of Ember Arrays to create a binding between firstQ
and the first Id in questions
array. Define your firstQ
property as a binding like this
App.Quiz = DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
questions: DS.hasMany('question', {async: true}),
firstQBinding: 'questions.firstObject'
});
Upvotes: 0