Reputation: 3
I tried to do something similar to this in a form, but get this error:
Started POST "/opinions" for 127.0.0.1 at 2019-01-03 17:11:12 -0800
Processing by OpinionsController#create as JS
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
Topic Load (0.0ms) SELECT "topics".* FROM "topics" WHERE "topics"."id" = ? LIMIT ? [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.0ms)
ActiveRecord::RecordNotFound (Couldn't find Topic with 'id'=):
app/controllers/opinions_controller.rb:6:in `create'
opinions_form.html.erb:
<%= form_for(opinion, :html=> {class:"form-horizontal", role:"form"}, remote: true) do |f| %>
<div class="form-group">
<div class="col-sm-12">
<%= f.text_area :content, rows:4, class: "form-control", placeholder: "Opinion" %>
</div>
</div>
<%= hidden_field_tag 'type_of', typeOf %>
<%= hidden_field_tag :topicId, :value => @topic.id %>
<% puts "ID: " + @topic.id.to_s %>
<div class="form-group">
<div class="col-sm-12">
<%= f.submit %>
</div>
</div>
<% end %>
Relevant code in controller:
def create
@opinion = Opinion.new(opinion_params)
@opinion.user = current_user
@opinion.topic = Topic.find(params[:opinion][:topicId])
if @opinion.save
flash[:success] = 'Opinion Added'
else
puts @opinion.errors.full_messages
flash[:danger] = 'Opinion not Added'
end
end
private
def opinion_params
params.require(:opinion).permit(:content, :type_of)
end
and finally, relevant code in the topic show page:
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "pro", :topic => @topic %>
</td>
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "con", :topic => @topic %>
</td>
Upvotes: 0
Views: 64
Reputation: 8787
As you can see in the request parameters:
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
The topicId
parameter is not nested under opinion
, so you need to change your finder to:
@opinion.topic = Topic.find(params[:topicId][:value])
You can also remove the superfluous value
key in your view:
<%= hidden_field_tag :topicId, @topic.id %>
Which would further simplify your finder:
@opinion.topic = Topic.find(params[:topicId])
As an aside. Note that idiomatic ruby calls for snake_case
in all identifiers. This won't change how your code works, but it will help other Ruby developers read your code.
Upvotes: 2