Rails:Param是零

时间:2016-03-16 12:28:41

标签: ruby-on-rails

我试图将一些参数从表单传递给视图,但我得到的只是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

new.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 %>

show.html.erb

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

<p>
<strong>Text:</strong>
<%= @quote.text %>
</p>
<% end %>

我使用Rails Dev Box,如果这有任何区别。

2 个答案:

答案 0 :(得分:1)

由于您提到记录确实已保存到数据库,因此新建和创建操作不应成为问题。但是,当您执行redirect_to @quote时,@ quote的id可用作show中的params [:id]。所以我认为,修改控制器中的show动作如下所示。

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

如果创建报价,这将在重定向页面上向用户发出友好的Flash消息。如果没有,它会使用引号#new来尝试另一次提交。

答案 1 :(得分:0)

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

 @quote = Quote.new

然后使用:

form_for(@quote)

在新视图中。

相关问题