如果使用name: "Run a Mile"
创建质询,那么我们如何制作布尔值key: true
?
我想将key
传递给真有超过50个名称,仅举例说明。
我想我会在create
中做到这一点,但那么控制器中的逻辑是不是很多?不确定它是否应该以某种方式进入模型,但我也担心那里有很多行。
def create
@challenge = current_user.challenges.build(challenge_params)
### Where should I put the below? ###
if @challenge.name == "Run a Mile"
@challenge.key = true
elsif @challenge.name == "Meditate 5 Min"
@challenge.key = true
elsif @challenge.name == "Tour Capital Building"
@challenge.key = true
elsif @challenge.name == "See Statue of Liberity"
@challenge.key = true
elsif @challenge.name == "Pait a Picture"
@challenge.key = true
else
end
### Where should I put the above? ####
if @challenge.conceal == true
@challenge.save
redirect_to @challenge
if @challenge.category == 'goal'
flash[:info] = 'CHALLENGE SECRETLY SAVED'
else
flash[:info] = "CHALLENGE SECRETLY SAVED. DON'T STRIKE OUT!"
end
elsif
@challenge.save
track_activity @challenge
redirect_to @challenge
if @challenge.category == 'goal'
flash[:info] = 'CHALLENGE SAVED'
else
flash[:info] = "CHALLENGE SAVED. DON'T STRIKE OUT!"
end
else
respond_modal_with @challenge
end
end
正如您所看到的,我的create
行动已经变得越来越复杂,甚至不是它的完整版本。
答案 0 :(得分:2)
我会在模型Challenge
(我猜)中这样做:
如果您每次更改姓名时都需要更改key
:
def name=(val)
...
case name
when 'a', 'b'
self.key = true
end
... # return with calling super method
end
如果您只需要在此处更改key
:
def reset_key
case name
when 'a', 'b'
self.key = true
end
end
# then @challenge.reset_key in controller
或者您可以避免设置key
(为什么我们需要更多状态?):
def key
case name
when 'a', 'b'
true
end
end