在我的应用中,用户可以创建个人资料,但在用户的个人资料为“公开”之前,需要填写一系列必填字段。
我正在进行after_update
回调,该回调会运行一系列检查以查看是否填写了必填字段。
以下是方法:
# User Model
after_update :check_public_status
def check_public_status
if self.name.blank? || self.state.blank? || self.city.blank? ||
self.high_school.blank? || self.recruit_year.blank? || self.birthday.blank? ||
self.stat(:height).blank? || self.stat(:weight).blank?
self.update_attribute :public, false
self.update_attribute :removed_from_listing, true
else
self.update_attribute :public, true
self.update_attribute :removed_from_listing, false
end
end
有没有更好的方法可以做到这一点,而没有那个讨厌的IF/Else
声明?
答案 0 :(得分:1)
这个怎么样:
after_update :update_public_status!
def update_public_status!
required_fields_present =
[
name, state, city,
high_school, recruit_year,
birthday, stat(:height), stat(:weight)
].all?
if required_fields_present
make_public!
else
make_private!
end
end
def make_public!
update_attribute :public, true
update_attribute :removed_from_listing, false
end
def make_private!
update_attribute :public, false
update_attribute :removed_from_listing, true
end