gpt4 book ai didi

ruby-on-rails - 将逻辑从 Controller 移动到 Rails 3 中的模型?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:58 24 4
gpt4 key购买 nike

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

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

谢谢!

艾略特

最佳答案

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

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. Controller :您需要检查 @person 是否实际保存(可能某些验证失败)。
  2. 模型:如果一个人在创建时总是需要指定价格,则使用回调(例如,before_validation)。否则,从 Controller 调用它,如上面的代码所示。

关于ruby-on-rails - 将逻辑从 Controller 移动到 Rails 3 中的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4818061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com