Ruby on rails Rails验证。需要其他资料。多种形式。不干燥

Ruby on rails Rails验证。需要其他资料。多种形式。不干燥,ruby-on-rails,forms,validation,Ruby On Rails,Forms,Validation,(Rails新手) 你好! 我觉得我在重用我的很多代码,我觉得必须有更好的方法来做到这一点。。。(我肯定有…) 我有一个设置页面,您可以在其中创建类别和过程(属于某个类别) 索引设置操作: def categories_and_procedures @prefs = @current_practice.preferences @category = @current_practice.categories.build @categories = @current_

(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
视图中有一个包含所有当前类别的列表和一个用于创建新类别的表单。类别模型中有一个验证(验证: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
def创建_类别
@category=@current_practice.categories.build(参数[:category])
如果@category.save
flash[:notice]=“新建类别:{@category.name}”
重定向到:操作=>“类别和过程”
其他的
##重复代码!!!!!!
@prefs=@current_practice.preferences
@category=@current_practice.categories.build
@categories=@current_practice.categories.all
@过程=@current_practice.procedures.build
##重复代码!!!!!!
render:action=>“类别和过程”
结束
结束
有没有办法把它移到一个可以调用的函数?帮手?过滤器? 我不知道

谢谢大家!

只要写:

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

categories\u和\u procedures
create\u categories

中调用它,谢谢!我试过了,有一次我按下submit,什么也没发生(当我预料到错误时)。我认为@category=@current_practice.categories.build正在替换错误。但当我使用设置方法时,我可以将其忽略,并将其分别放在“类别”和“过程”中。再次感谢!
def setup_object
  @prefs = @current_practice.preferences

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