轨道:参数为零



我正在尝试将一些参数从表单传递到视图,但我得到的只是param is missing or the value is empty: quotes.我已经检查了数据库,输入保存在那里,但由于某种原因,数据在到达视图的途中变得nil

我正在将:quotes参数从视图传递到控制器,应该是这样,不是吗?

quotes_controller.rb

class QuotesController < ApplicationController
def new
end
def create
  @quote = Quote.new(quote_params)
  @quote.save
  redirect_to @quote
end
def show
  @quote = Quote.find(quote_params[:id])
end
private
  def quote_params
    params.require(:quotes).permit(:title, :text)
  end
end

新.html.erb

<h2>Add Quote</h2>
<%= form_for :quotes, url: quotes_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>

显示.html.erb

<h2>Saved Quotes</h2>
<p>
<strong>Title:</strong>
<%= @quote.title %>
</p>
<p>
<strong>Text:</strong>
<%= @quote.text %>
</p>
<% end %>

我正在使用Rails Dev Box,如果这有什么不同的话。

由于您提到记录确实被保存到数据库中,因此新建和创建操作应该不是问题。但是,当您这样做时redirect_to @quote@quote的 id 在 show 中以参数[:id] 的形式提供。所以我认为,按如下方式修改控制器中的显示操作应该有效。

def show
  @quote = Quote.find(params[:id])
end

另一方面,您应该考虑修改创建操作,以考虑未通过验证或未保存到数据库的新报价单的提交。

def create
  @quote = Quote.new(quote_params)
  if @quote.save
    flash[:success] = "Successfully created the new quote..."
    redirect_to @quote
  else
    render 'new'
  end
end

如果创建了报价,这将导致在重定向页面上向用户发送友好的闪光消息。如果没有,它会呈现引号#new以尝试另一个提交。

该错误是new操作的视图。您没有设置任何实例变量quotes。实际上那里应该有quote,但没有。添加new

 @quote = Quote.new

然后使用:

form_for(@quote)

在您的新视图中。

最新更新