当我在 number_field
中输入内容时并将表单发布到 Controller ,Rails 无法保存,因为我有一个数字验证:
validates :rating, numericality: { greater_than: 0, less_than: 6 }
我通过这段代码调试了 Controller :
raise "It exploded into pieces!" unless @comment.save
我用于调试的异常表示我的
:rating
是一个字符串而不是一个整数。在此之前,我为 @comment
渲染了 json 错误那就是说 :rating
不是一个数字。这些对于发现问题非常有用,但我找不到解决问题的任何解决方案。我检查了数据库架构,它说
:rating
应该是一个整数,如: t.integer "rating"
我不知道此时该怎么办。有人可以帮助我吗?先感谢您。
附言我用
number_field
.P.P.S.
在我的 Controller 中:
def ccreate
@comment = Comment.new(params.permit(:rating, :body, :name, :game_id))
raise "It exploded into pieces!" unless @comment.save
end
在我看来:
<% if @comments.count < 10 %>
<%= form_for(comment_path) do |f| %>
<div class="field">
<%= f.label :rating %><br>
<%= f.number_field :rating %>
</div>
<div class="field">
<%= f.label :body %><br>
<%= f.text_area :body %>
</div>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<% end %>
最佳答案
这是一个强大的参数。允许:评论,然后是属性
params.require(:comments).permit(:rating, :body, :name, :game_id)
并且,使用 form_for @comment,而不是 comment_path
关于ruby-on-rails - Rails 4 整数字段返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890047/