我正在使用Rails 4""敏捷Web开发教程和我在尝试为flash哈希值分配值时遇到了一个小问题,这将在导航栏下面的应用程序中创建一条flash消息。当我运行我的测试套件时,我收到此错误:
TypeError: no implicit conversion of Hash into Integer
app/controllers/line_items_controller.rb:34:in `[]'
app/controllers/line_items_controller.rb:34:in `block (2 levels) in create'
app/controllers/line_items_controller.rb:32:in `create'
test/controllers/line_items_controller_test.rb:21:in `block (2 levels) in <class:LineItemsControllerTest>'
test/controllers/line_items_controller_test.rb:20:in `block in <class:LineItemsControllerTest>'
这是line_items_controller中的创建操作:
def create
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, :flash[success: 'Line item was successfully created.'] }
format.json { render :show, status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
这就是flash消息在应用程序中呈现的方式。这来自application.html.erb布局文件。它使用字符串插值根据flash哈希值放置的值自动更改引导类。
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
我非常确定它只是一个简单的格式问题(在format.html行中..)但我无法弄清楚如何修复它!所有帮助表示赞赏:)
答案 0 :(得分:1)
:flash[success: 'Line item was successfully created.']
您尝试渲染上面的Flash消息的方式是错误的。
你应该这样做:
flash[:success] = 'Line item was successfully created.'
See this了解有关如何在哈希值中设置键值的更多信息。
替换:
format.html { redirect_to @line_item.cart, :flash[success: 'Line item was successfully created.'] }
使用:
format.html {
flash[:success] = 'Line item was successfully created.'
redirect_to @line_item.cart
}
您也可以使用:
format.html { redirect_to @line_item.cart, flash: { success: 'Line item was successfully created.' } }
这两个都应该有效并解决你的问题。