我尝试以某种形式执行类似于this的操作,但出现此错误:
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 %>
控制器中的相关代码:
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
最后是主题显示页面中的相关代码:
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "pro", :topic => @topic %>
</td>
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "con", :topic => @topic %>
</td>
答案 0 :(得分:2)
如您在请求参数中所见:
Parameters: {"utf8"=>"✓", "opinion"=>{"content"=>"This is an opinion"}, "type_of"=>"pro", "topicId"=>"{:value=>2}", "commit"=>"Create Opinion"}
topicId
参数未嵌套在opinion
下,因此您需要将查找器更改为:
@opinion.topic = Topic.find(params[:topicId][:value])
您还可以删除视图中多余的value
键:
<%= hidden_field_tag :topicId, @topic.id %>
这将进一步简化您的查找器:
@opinion.topic = Topic.find(params[:topicId])
顺便说一句。请注意,惯用的红宝石要求所有标识符中的snake_case
。这不会改变代码的工作方式,但是会帮助其他Ruby开发人员阅读您的代码。