首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新/验证大规模更新rails关联

更新/验证大规模更新rails关联
EN

Code Review用户
提问于 2013-01-25 22:06:53
回答 1查看 1.2K关注 0票数 2

我的菜谱模型如下

代码语言:javascript
复制
has_many :quantities
has_many :ingredients, :through => :quantities, :uniq => true
has_many :sizes, :through => :quantities, :uniq => true

以及试图重构的控制器动作

代码语言:javascript
复制
class Admin::QuantitiesController < Admin::AdminController
  layout 'admin'

  authorize_resource :class => :controller

  def create
    recipe        = Recipe.find(params[:recipe_id])
    values      = params[:quantity][:ingredient]
    @quantities = Quantity.find(values.keys)

    @quantities_errors = {}
    @quantities.each do |quantity|
        if quantity.value != values[quantity.id.to_s]
            quantity.value = values[quantity.id.to_s]
            if quantity.valid?
                quantity.save
            else
                @quantities_errors[quantity.id] = quantity.errors.messages
            end
        end
    end

    unless @quantities_errors
        redirect_to edit_admin_recipe_path(recipe), notice: 'Ingredients was successfully added.'
    else
        redirect_to edit_admin_recipe_path(recipe), alert: @quantities_errors
    end

  end

end
EN

回答 1

Code Review用户

回答已采纳

发布于 2013-01-27 19:53:47

一些注意事项:

  • 这是一个edit_admin_recipe表单,所以您应该发布到Admin::RecipesController#update
  • 使用Rails基础设施为模型(接受_巢式_属性_为)保存嵌套数据。控制器必须保持简单和干净。
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/20916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档