Skip to content

Instantly share code, notes, and snippets.

@dmgarland
Created May 24, 2013 19:05
Show Gist options
  • Select an option

  • Save dmgarland/5645797 to your computer and use it in GitHub Desktop.

Select an option

Save dmgarland/5645797 to your computer and use it in GitHub Desktop.
app.models.Project = Backbone.Model.extend({
url: function() {
var url = '/users/' + this.user.id + '/projects';
if(!this.isNew()) {
url += '/' + this.id;
}
return url;
},
initialize: function() {
this.skills = this.skills || new app.collections.SkillList();
this.skills.model = app.models.Skill; // Don't know why but this worked
},
validate: function() {
if(this.attributes.url === "") {
return "Argh!";
}
},
parse: function(response) {
var skills_json = response.skills;
this.skills = new app.collections.SkillList(skills_json);
return response;
},
toJSON: function() {
var sa = [];
this.skills.forEach(function(skill) {
sa.push({ id: skill.get("id"), name: skill.get("name")});
});
var json = { project : _.extend(this.attributes, { 'skills_attributes': sa }) };
delete json.project.skills;
return json;
}
});
class Project < ActiveRecord::Base
attr_accessible :body, :title, :url, :user_id, :skills_attributes
belongs_to :user
has_many :skills
accepts_nested_attributes_for :skills
def as_json(options = {})
super({ :include => { :skills => { :only => [:id, :name] } },
:only => [:id, :title, :body, :url, :user_id] }.merge(options))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment