【问题标题】:Rails validations. Needs data from other stuff. Multiple forms. Not being DRYRails 验证。需要其他东西的数据。多种形式。不干燥
【发布时间】:2010-02-13 20:26:00
【问题描述】:

(Rails 新手)

你好!

我觉得我正在重用我的很多代码,我觉得必须有更好的方法来做到这一点......(我确信有......)

我有一个设置页面,您可以在其中创建类别和程序(属于一个类别)。

索引设置操作:

def categories_and_procedures   
    @prefs = @current_practice.preferences

    @category = @current_practice.categories.build
    @categories = @current_practice.categories.all
    @procedure = @current_practice.procedures.build
end

视图中有一个包含所有当前类别的列表和一个用于创建新类别的表单。在 Category 模型中是一个验证(validates_uniqueness_of :name)。

创建动作:

    def create_category
    @category = @current_practice.categories.build(params[:category])
    if @category.save
        flash[:notice] = "New category created: <i>#{@category.name}</i>"
        redirect_to :action => "categories_and_procedures"
    else
        ##Duplicate code!!!!!!
        @prefs = @current_practice.preferences

        @category = @current_practice.categories.build
        @categories = @current_practice.categories.all
        @procedure = @current_practice.procedures.build
        ##Duplicate code!!!!!!
        render :action => "categories_and_procedures"
    end
end

有没有办法可以将它移动到我可以调用的函数中?帮手?过滤器? 我不知道。

谢谢!

【问题讨论】:

    标签: ruby-on-rails forms validation


    【解决方案1】:

    只写:

    def create_category
      @category = @current_practice.categories.build(params[:category])
      if @category.save
        flash[:notice] = "New category created: <i>#{@category.name}</i>"
        redirect_to :action => "categories_and_procedures"
      else
        categories_and_procedures
        render :action => "categories_and_procedures"
      end
    end
    

    添加一些设置方法会更好看:

    def setup_object
      @prefs = @current_practice.preferences
    
      @category = @current_practice.categories.build
      @categories = @current_practice.categories.all
      @procedure = @current_practice.procedures.build
    end
    

    并从categories_and_procedurescreate_category 调用它。

    【讨论】:

    • 啊,谢谢!我试过了,一旦我按下提交,什么都没有发生(当我期待错误时)。我认为 @category = @current_practice.categories.build 正在替换错误。但是,当我使用 set_up 方法时,我可以将其忽略并单独放入“categories_and_procedures”中。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-08-27
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多