尝试使用Rails中的嵌套资源创建新对象时遇到了问题。我的路由设置为:
resources :coins do
resources :questions
end
当我尝试创建新问题时,它不会保存。我被重定向到了问题'页面和来自'新'的表单包含输入内容的所有页面都保留在页面上(而不是保存时应该存在的问题列表)。我的控制器如下:
class QuestionsController < ApplicationController
before_action :find_question, only: [:show]
before_action :find_coin
before_action :authenticate_user!, except: [:index, :show]
def index
@questions = Question.where(coin_id: @coin.id).order("created_at DESC")
end
def show
end
def new
@coin
@question = current_user.questions.build
end
def create
@question = current_user.questions.build(question_params)
if @question.save
redirect_to coin_question(@question.coin_id, @question.id)
else
render 'new'
end
end
private
def find_question
@question = Question.find(params[:id])
end
def find_coin
@coin = Coin.find(params[:coin_id])
end
def question_params
params.require(:question).permit(:content, :ques_num, :coin_id)
end
end
我的&#39;新&#39;页面然后显示以下表格:
<%= simple_form_for @question, url: coin_questions_path(@coin.id) do |f| %>
<%= f.input :ques_num %>
<%= f.input :content %>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
这是我第一次使用嵌套资源并将其绊倒一点。我真的很感激这里的任何帮助。
答案 0 :(得分:1)
您的创建操作失败,因此它正在执行assertThat(Object actual)
语句,该语句只是使用您输入的数据呈现您的表单。最简单的方法是查看日志文件,看看保存它的原因。
转到else
,如果您正在使用Mac按下命令,则向下箭头会将您一直带到文件底部。
您也可以查看模型验证。如果您没有设置闪存或未将错误输出到视图,则验证可能导致表单无法保存,您将看不到错误。
您可以像这样添加一些错误处理
/log/development.log
为您的控制器尝试
<%= form_with(model: question, local: true) do |form| %>
<% if question.errors.any? %>
<div id="error_explanation">
<h2 class="text-danger"><%= pluralize(question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul class="text-danger">
<% question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
答案 1 :(得分:0)
我认为创建问题会有错误。
if @question.save
redirect_to coin_question(@question.coin_id, @question.id)
else
render 'new'
end
因此,如果记录有任何保存错误,它将重定向到新表单。
只需使用以下代码即可了解创建问题的错误
def create
@question = current_user.questions.build(question_params)
if @question.save
flash[:notice] = 'Question created'
redirect_to coin_question(@question.coin_id, @question.id)
else
flash[:notice] = 'Some error here!'
render 'new'
end
end
您需要设置闪光灯以显示闪光灯错误。