【问题标题】:How can I CREATE multiple records at once in Rails POST CREATE controller?如何在 Rails POST CREATE 控制器中一次创建多个记录?
【发布时间】:2014-11-25 20:08:19
【问题描述】:

我目前有几个模型,例如 User、UserMovieList 和 UserMovieListItem。

例如,用户可以创建他们最喜欢的喜剧电影或最喜欢的恐怖电影的列表。创建新列表后,假设“我最喜欢的恐怖电影”,然后他们可以将条目添加到列表中。他们可能会添加“Friday the 13th”和“The Ring”,然后保存。

现在我正在将这 2 部电影以 2 个单独的 POSTS 添加到 Web 服务器,以便将它们添加到 UserMovieListItem。

我希望能够在 1 个 POST 中添加它们。

{
  "user_movie_list_item":
  {
    "title": "Friday the 13th"
  }     
}

我希望能够发送

{
  "user_movie_list_item":
  {
    "title": "Friday the 13th"
  },
  {
    "title": "The Ring"
  }  
}

1) 这是 JSON 发送多个条目的正确格式吗?

2) 如何在我的控制器中执行此操作?

现在我有...

def create
    if authenticate_user
        user_movie_list = @current_user.user_movie_lists.find_by_id(params[:user_movie_list_id])
        user_movie_list_item = user_movie_list.user_movie_list_items.new(user_movie_list_item_params)
        if (user_movie_list_item.save!)
            respond_with :api, :v1, @current_user, user_movie_list, user_movie_list_item, location: nil, serializer: Api::V1::UserMovieListItemSerializer
        else
            render json: { error: "Could not create new User Movie List Item."}, status: :unprocessable_entity
        end         
    else
        render json: { error: "User is not signed in." }, status: :unauthorized
    end
end

如何才能一次添加多条记录?

【问题讨论】:

  • 我建议将“if authenticate_user”替换为“before_action :authenticate_user!”。

标签: ruby-on-rails rest post


【解决方案1】:

在您的模型中,您可以像这样覆盖分配:

def user_movie_list=(list)
  list.each do | l |
     ml = user_movie_list_items.new
     ml.title = l.title

     ... # configure your list

     ml.save!
  end
end

JSON 列表是:

{ "my_list": [{"title": "blah"}, {"title": "foo"}, ... ] }

【讨论】:

  • 谢谢。如何将参数定义为 JSON 数组? def user_movie_list_item_params params.require(:user_movie_list_item).permit(:user_movie_list_id, :title, ) end 或者你是说我可以去 def user_movie_list_item_params=(list) 并迭代它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多