如何解决Rails 3 app-不存储值
| 在我的控制器中,一大堆数字被弄乱了。将百分比乘以100,以便可以将它们存储为整数。以下是部分列表:tot = @mot[1] + @mot[2] + @mot[3]
exec_pct = @mot[3] / tot * 100
tact_pct = @mot[2] / tot * 100
strat_pct = @mot[1] / tot * 100
然后,应将这些值写入用户记录,如下所示:
current_user.update_attributes(:strat_pct => strat_pct.to_i,:tact_pct => tact_pct.to_i,:exec_pct => exec_pct.to_i )
数据库具有应存储数据的空值。
这是数据库架构的相关部分:
t.integer \"strat_pct\"
t.integer \"tact_pct\"
t.integer \"exec_pct\"
更新-
为了进行测试,我通过插入整数来消除计算问题,如下所示:
current_user.update_attributes(:strat_pct => 1,:tact_pct => 2,:exec_pct => 3 )
和:
p current_user.update_attributes(:strat_pct => 1,:exec_pct => 3 )
这些字段仍然为空。
更新2-用户模型:
class User < ActiveRecord::Base
devise :database_authenticatable,:registerable,:recoverable,:rememberable,:trackable,:validatable
attr_accessible :first_name,:last_name,:email,:password,:password_confirmation,:remember_me,:login
validates :first_name,:presence => true
before_create :create_login
def create_login
self.login = \"#{last_name.capitalize},#{first_name.capitalize}\"
end
has_many :answers
has_many :invitations
has_many :feedbacks
end
谢谢你的帮助。
解决方法
有几件事可能是错误的。
首先,尝试:
p current_user.update_attributes(:strat_pct => strat_pct.to_i,:tact_pct => tact_pct.to_i,:exec_pct => exec_pct.to_i )
从文档中:
如果由于连接或远程服务错误而导致保存失败,则会引发异常。如果由于资源无效导致保存失败,则将返回false。
令我震惊的另一件事是,您的逻辑可能会为所有内容返回0:
tot = @mot[1] + @mot[2] + @mot[3] #assume [0,100,200,300] = 600
exec_pct = @mot[3] / tot * 100 #300 / 600000 (integers)= 0
tact_pct = @mot[2] / tot * 100 #200 / 600000 (integers)= 0
strat_pct = @mot[1] / tot * 100 #100 / 600000 (integers)= 0
也许你的意思是:
tot = (@mot[1] + @mot[2] + @mot[3]).to_f #assume [0,300] = 600.0
exec_pct = (@mot[3] / tot) * 100 #300 / 600000.0 (float)= 50.0
tact_pct = (@mot[2] / tot) * 100 #200 / 600000.0 (float)= 33.333
strat_pct = (@mot[1] / tot) * 100 #100 / 600000.0 (float)= 16.666
在ruby中,如果要进行浮点运算,则至少一个值必须是浮点数。我还假设您正在执行百分比,因此我在除法运算周围添加了括号,因为这需要首先执行。
另外,我可能是错的,但是看起来您不小心对数组进行了1索引。数组索引从0开始。如果是这种情况,则可以将代码更改为:
@mot = [100,300]
total = @mot.inject(:+).to_f
@mot.map {|x| ((x/total.to_f)*100).to_i} #result => [16,33,50]
current_user.update_attributes(:strat_pct =>@mot[0],:tact_pct => t@mot[1],:exec_pct => @mot[2] )
编辑
您的问题在这里:
validates :first_name,:last_name,:email,:password,:password_confirmation,:presence => true
您正在尝试更新属性,但是由于密码和password_confirmation不是真实字段,因此将丢失。将该行更改为:
validates :first_name,:presence => true
validates :password,:presence => true,:on => :create
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。