【发布时间】:2019-11-19 06:46:35
【问题描述】:
我正在制作一个 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:" %>
我希望这个产品会被创造出来。
编辑:
我试图在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
```
【问题讨论】:
-
错误的完整堆栈跟踪是什么?
-
问题是
@categories是nil因为你没有在你的create方法中定义它。 -
那要怎么解决呢?
-
“它仍然无法正常工作” ...是否有不同的错误?同样的错误?
标签: ruby-on-rails ruby methods