我正在开发一个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
HTML代码:
<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:" %>
我希望将创建产品。
编辑:
我尝试在@categories
方法上声明create
,但仍然无法正常工作:
@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
```
答案 0 :(得分:0)
使用map
方法检查new
调用。
@categories = Category.all.map{ |c| [c.name, c.id] }
这可能是错误的原因。如果未找到任何记录,则'AсtiveRecord'返回一个空数组,但是无论如何我会验证输出,以防意外。
答案 1 :(得分:0)
似乎您从AR查询中收到零。要处理此类错误,您可以尝试以下操作:
@categories = Category.all.to_a.map{ |c| [c.name, c.id]}
但是由于没有任何结果,因此结果将为0。