我正在制作一个Rails应用程序,上面会有一些"产品"的东西。产品将有照片,名称,类别,代码和描述。
我尝试了很多方法,但没有一种奏效。
Products_controller的 NEW 和 CREATE 方法:
def new
if !logged_in?
redirect_to root_path
end
if logged_in?
@product = current_user.products.build
@categories = Category.all.map{ |c| [c.name, c.id] }
end
end
def create
@product = current_user.products.build(product_params)
@product.category_id = params[:category_id]
if @product.save
redirect_to root_path
else
render 'new'
end
网页代码:
<div class="col-md-6 col-md-offset-3">
<div class="deniso">
<% <h1>Shto Produkt:</h1>
<%= simple_form_for @product, :html => {:multipart => true} do |f| %>
<%= f.file_field :product_img %>
<div class="cate">
<%= select_tag(:category_id, options_for_select(@categories), :prompt => "Zgjidhni kategorine:") %>
</div>
<h4>Emri i produktit</h4>
<%= f.input :title, label: "Emri i Produktit:" %>
<h4>Kodi</h4>
<%= f.input :kodi, label: "Kodi:" %>
<h4>Qmimi<h4>
<%= f.input :qmimi, label: "Qmimi:" %>
<h4>Pershkrimi</h4>
<%= f.input :pershkrimi, label: "Pershkrimi:" %>
<div class="btn btn-1">
<%= f.button :submit %>
</div>
<% end %>
</div>
<%= link_to "Kthehuni mbrapa", root_path, class: "btn-custom2" %>
</div>
</div>
</div>
错误代码:
NoMethodError in Products#create
Showing C:/Users/PC/Desktop/Npshkodra/app/views/products/new.html.erb where line #12 raised:
undefined method `map' for nil:NilClass
Did you mean? tap
<%= f.file_field :product_img %>
<div class="cate">
<%= select_tag(:category_id, options_for_select(@categories), :prompt => "Zgjidhni kategorine:") %>
</div>
<h4>Emri i produktit</h4>
<%= f.input :title, label: "Emri i Produktit:" %>
我希望该产品将被创建。
编辑:我试图在create
方法上声明@categories
,但它仍然不起作用:
@categories = Category.all.map{ |c| [c.name, c.id] }
@product = current_user.products.build(product_params)
@product.category_id = params[:category_id]
if @product.save
redirect_to root_path
else
render 'new'
end
end
```
检查new
方法中的map
调用。 @categories = Category.all.map{ |c| [c.name, c.id] }
这可能是导致错误的原因。如果没有找到记录,'AсtiveRecord' 会返回一个空数组,但无论如何我都会验证输出,以防发生意外情况。
似乎您从 AR 查询中收到零。要处理此类错误,您可以尝试以下操作:
@categories = Category.all.to_a.map{ |c| [c.name, c.id]}
但是结果将是 0,因为没有任何。