Ruby on rails Rails 4整数字段返回字符串
当我在Ruby on rails Rails 4整数字段返回字符串,ruby-on-rails,forms,validation,types,integer,Ruby On Rails,Forms,Validation,Types,Integer,当我在number\u字段中输入某个内容并将表单发布到控制器时,Rails无法保存,因为我有一个数字验证: validates :rating, numericality: { greater_than: 0, less_than: 6 } 我通过以下代码调试了控制器: raise "It exploded into pieces!" unless @comment.save 我用于调试的异常表示我的:rating是字符串而不是整数。在此之前,我为@comment呈现了json错误,这表示:
number\u字段中输入某个内容并将表单发布到控制器时,Rails无法保存,因为我有一个数字验证:
validates :rating, numericality: { greater_than: 0, less_than: 6 }
我通过以下代码调试了控制器:
raise "It exploded into pieces!" unless @comment.save
我用于调试的异常表示我的:rating
是字符串而不是整数。在此之前,我为@comment
呈现了json错误,这表示:rating
不是一个数字
这些对发现问题非常有用,但我找不到任何解决问题的方法。我检查了数据库模式,它说:rating
应该是一个整数,如:
t.integer "rating"
现在我不知道该怎么办。有人能帮我吗?先谢谢你
注意:我使用数字\字段
p.p.S。
在我的控制器中:
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 %>
我认为您需要正确设置表单,我认为如果表单按其应该的方式发布,验证将正常工作:
注释\u controller.rb
def new
@comment = Comment.new
end
def create
@comment = Comment.new(comment_params)
raise "It exploded into pieces!" unless @comment.save
end
private
def comment_params
params.require(:comment).permit(:rating, :body, :name, :game_id)
end
在这里,我们正在更改强参数,以要求在参数中使用新的注释键(这将是对下面视图的第二次更改的结果)。我还把它移到了一个私人函数中来清理它
那么在你看来:
<% if @comments.count < 10 %>
<%= form_for(@comment) 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 %>
这在模型实例中使用了形式_for标记,我认为这应该解决这个问题。这是一个强大的参数。允许:注释,然后是属性
params.require(:comments).permit(:rating, :body, :name, :game_id)
并且,在comment\u controller.rb中使用@comment的形式,而不是comment\u路径
def new
@comment = Comment.new
end
def create
@comment = Comment.new(comment_params)
raise "It exploded into pieces!" unless @comment.save
end
private
def comment_params
params.require(:comment).permit(:rating, :body, :name, :game_id)
end
@rating=params[:comment][:rating].to_i
要将评级的每个输入转换为整数,rails的错误表示评级不是数字?是的,异常的“参数”部分表示hash中的passonly\u integer:true
。您可以重新启动rails服务器吗?瞎猜是我干的pI做到了,同样的结果。你说的是验证散列,对吧,阿斯兰?我刚刚更新了答案,更详细地介绍了我所做的更改。未定义的方法“comments\u path”用于“注释中只有新的”。@avaragecoder没有为注释定义路由吗?是的,你需要添加“resources:comments,only:[:new,:create]”(没有引号)到您的路由文件。然后,你可以根据需要向唯一的部分添加更多方法。你看,我的新功能不存在,评论是在游戏#show中创建的,它转到comments#createoh,@comment不再存在