vendredi 4 septembre 2015

How to duplicate and save RoR models along with their has_one/many kiddies

I'm very new to Angular and Rails and I've been really stuck so any help would be REALLY appreciated! I can find lots of info for small tasks but I'm having a lot of trouble finding any guides or complete examples for application architecture.

I'm making an application with users, who each have posts. Each post has_one template and has_one info. Rails Model relationship is as follows:

user has_many posts
posts has_one info, has_one template, belongs_to users
info belongs_to posts, template belongs_to posts

When a user creates a new post, I need "template" and "info" to be automatically filled with data. I also need the user to have a "duplicate" button to duplicate an existing post.

I'm updating/retrieving the database info by sending json in angular. For example:

createPost = function() {
  return $http.post('/posts.json', post).then(function(response){
    posts.push(response.data);
  });
};

Then the route points the request to a rails controller action that all look similar to this:

def create
  posts = current_user.posts
  respond_with posts.create(micropost_params)
end

How do I go about getting the "info" and "template" updated since they are not in the same Rails model as the post? Can I create a single action that will do it somehow? Can I pass a single json object from angular? It seems like if I send one post request for each model that things could go wrong.

Json array of a user's posts if it makes this easier to visualize:

[
 {
    "id": 2,
    "user_id": 2,
    "created_at": "2015-09-01T10:17:01.897Z",
    "updated_at": "2015-09-01T10:17:01.897Z",
    "info": {
        "group": "10.001"
    },
    "template": {
        "name": "template",
        "templateIndex": 1,
        "shared": true
    }
 },
 {
    "id": 1,
    "user_id": 2,
    "created_at": "2015-09-01T10:17:01.897Z",
    "updated_at": "2015-09-01T10:17:01.897Z",
    "info": {
        "group": "10.001"
    },
    "template": {
        "name": "template",
        "templateIndex": 1,
        "shared": true
    }
 }
]

Aucun commentaire:

Enregistrer un commentaire