将逻辑从控制器移动到 rails 3 中的模型? [英] Moving logic from controller to model in rails 3?

查看:33
本文介绍了将逻辑从控制器移动到 rails 3 中的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在构建一个竞赛应用程序,我可以很容易地看出我在控制器中放置了太多的逻辑.我怎样才能将这种类型的逻辑切换到模型?(这里重要的不是逻辑本身 - 它远未完成 - 我只是想了解如何将其移出控制器).

I've been building a contest application, and I can easily tell I've been putting wayyyy too much logic in the controller. How can I go about switch this type of logic to the model? (whats important here isn't the logic itself - its far from finished - I'm just trying to understand how to move it out of the controller).

控制器:

def create
    @person = Person.new(params[:person])
    @yournum = rand(100)
    @day = Day.find_by_id(1)
    @prereg = Prereg.find_by_email(@person.email)

    if @preg != nil
      @person.last_name = @prereg.name
    end 

    if @day.number == 1


      if @yournum <= 25
      @person.prize_id = 2
      elsif @yournum > 25 && @yournum <=50
      @person.prize_id = 1
      elsif @yournum > 51 && @yournum <=75
      @person.prize_id = 3
      elsif @yournum > 76 && @yournum <=100
      @person.prize_id = 4
      end

    elsif @day.number == 2

      if @yournum <= 25
      @person.prize_id = 2
      elsif @yournum > 25 && @yournum <=50
      @person.prize_id = 1
      elsif @yournum > 51 && @yournum <=75
      @person.prize_id = 3
      elsif @yournum > 76 && @yournum <=100
      @person.prize_id = 4
      end

    elsif @day.number == 3      

      if @yournum <= 50
      @person.prize_id = 2
      elsif @yournum > 51 && @yournum <=90
      @person.prize_id = 1
      elsif @yournum > 91 && @yournum <= 95
      @person.prize_id = 3
      elsif @yournum > 96 && @yournum <=100
      @person.prize_id = 4
      end

    end

    @person.save
    redirect_to @person

  end

型号:

class Person < ActiveRecord::Base
  belongs_to :prize

end

谢谢!

艾略特

推荐答案

确实,这是一个非常丑陋的控制器.正如您所说,解决方案很简单:将所有逻辑移至模型:

Indeed, that's a pretty ugly controller. As you say, the solution is easy: move all the logic to the model:

def create
  @person = Person.new(params[:person])
  @person.set_price

  if @person.save
    redirect_to @person
  else
    flash[:error] = ...
    render :action => 'new'
  end
end

class Person
  def set_price
    # your logic here
  end
end    

注意:

  1. 控制器:你需要检查 @person 是否真的被保存了(可能某些验证失败了).
  2. 模型:如果一个人在创建时总是被分配一个价格,那么使用回调(例如before_validation).否则,从控制器调用它,如上面的代码所示.
  1. Controller: you need to check if @person was actually saved (maybe some validation failed).
  2. Model: If a person has always to be assigned a price on creation, then use a callback (before_validation, for example). Otherwise, call it from the controller as shown the code above.

这篇关于将逻辑从控制器移动到 rails 3 中的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆