Reputation: 797
When I enter something into a number_field
and post the form to the controller, Rails can't save because i have a numericality validation:
validates :rating, numericality: { greater_than: 0, less_than: 6 }
I debugged the controller by this piece of code:
raise "It exploded into pieces!" unless @comment.save
The exception I used for debugging said that my :rating
was a string instead of an integer. Before this, i rendered the json errors for @comment
and that said that :rating
was not a number.
These are very useful to spot the problem, but I can't find any solutions to fix the problem. I checked the database schema and it says that :rating
should be an integer, as in:
t.integer "rating"
I don't know what to do at this point. Can somebody help me? Thank you in advance.
P.S. I use number_field
.
P.P.S. In my controller:
def ccreate
@comment = Comment.new(params.permit(:rating, :body, :name, :game_id))
raise "It exploded into pieces!" unless @comment.save
end
In my view:
<% 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 %>
Upvotes: 4
Views: 18212
Reputation: 1
try this in the comment_controller.rb
@rating = params[:comment][:rating].to_i
to make every input of the ratings to be converted as integer
Upvotes: 0
Reputation: 372
It's a strong params thing. Permit :comments, then the attributes
params.require(:comments).permit(:rating, :body, :name, :game_id)
and, use form_for @comment, not comment_path
Upvotes: 3
Reputation: 2970
I think you need to setup the form properly, I think the validation will work fine if the form posts as it should:
comments_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
There we are changing the strong params to require the new comment key in params (which will be the result of the second change to the view below). I also moved this into a private function to clean this up.
So then in your view:
<% 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 %>
This uses the form_for tag with the model instance which should, I think, solve this issue.
Upvotes: 0