has_many通过Rails关联AngularJS'POST'$资源,如何传入数组?

时间:2016-04-29 04:44:51

标签: ruby-on-rails angularjs

我试图通过AngularJS ngResource'POST'传入一个数组但是遇到了麻烦。 ngResource似乎不喜欢通过params传入数组?有没有办法解决这个问题,以便做出正确的关联?

控制器

ctrl.recipe = new RecipeService();

ctrl.ingredients = IngredientService.query();

ctrl.recipe.carbs = 0;
ctrl.recipe.fat = 0;
ctrl.recipe.protein = 0;
ctrl.recipe.ingredient_ids = [];

ctrl.addRecipe = function() {
 if (Auth.isAuthenticated()) {
   ctrl.recipe.$save(function() {
     var action = "created"
     alerts.recipeSuccessAlert(action);
     $location.path('recipes');
   }); 
 } else {
    alerts.loginAlert();
  };
};

ctrl.addIngredient = function(ingredient) {
  ctrl.recipe.ingredient_ids.push(ingredient.id.toString());
  console.log(ctrl.recipe.ingredient_ids)
};

Strong Params Rails

def recipe_params 
  params.require(:recipe).permit(:title, :serves, :method, :time, :carbs, :fat, :protein, :meal_type, :user_id, :calories, ingredient_ids: []) 
end 

输出

Started POST "/api/v1/recipes.json" for ::1 at 2016-04-29 12:19:52 +1000
Processing by Api::V1::RecipesController#create as JSON
Parameters: {"carbs"=>0, "fat"=>0, "protein"=>2, "ingredient_ids"=>["3", "2"], "title"=>"jklsad", "serves"=>4, "meal_type"=>"Breakfast", "method"=>"jkasljasdk", "time"=>"5", "calories"=>8, "recipe"=>{"title"=>"jklsad", "serves"=>4, "method"=>"jkasljasdk", "time"=>"5", "carbs"=>0, "fat"=>0, "protein"=>2, "meal_type"=>"Breakfast", "calories"=>8}}
User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
(0.4ms)  BEGIN
SQL (0.4ms)  INSERT INTO "recipes" ("title", "serves", "method", "time", "carbs", "fat", "protein", "meal_type", "calories", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["title", "jklsad"], ["serves", 4], ["method", "jkasljasdk"], ["time", 5], ["carbs", 0.0], ["fat", 0.0], ["protein", 2.0], ["meal_type", "Breakfast"], ["calories", 8.0], ["user_id", 1], ["created_at", "2016-04-29 02:19:52.029494"], ["updated_at", "2016-04-29 02:19:52.029494"]]
 (7.6ms)  COMMIT
Completed 200 OK in 17ms (Views: 0.6ms | ActiveRecord: 8.7ms)

0 个答案:

没有答案