【发布时间】:2021-08-11 12:06:25
【问题描述】:
当 id do /products/1 显示我的产品时 products/%23<Product::ActiveRecord_Relation:0x00007f11426994c0>
这对于我点击的每个链接都是不同的。现在的问题是当我点击链接时它显示Couldn't find Product with 'id'=#<Product::ActiveRecord_Relation:0x00007f11426994c0> 它应该不做id 而不是ActiveRecord ???
这是我的产品控制器
class ProductsController < ApplicationController
include ProductsHelper
# before_action :logged_in?, only: [:index, :show, :edit]
before_action :admin_only, only: %i[destroy reset_votes]
def index
@products = Product.all
end
def edit
@product = Product.find(params[:id])
end
def create
@product_params = params.require(:product).permit(%i[name size image])
end
def destroy
end
def add_to_cart
id = params[:id].to_i
if session[:cart].include?(id)
session[:cart].delete(id)
else
session[:cart] << id
end
redirect_back(fallback_location: root_path)
end
def show
@products = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
product_params = params.require(%i[name size image])
@product.update_attributes(product_params)
end
private
def product_params
params.require(:category).permit(%i[name size image])
end
end
这是我的产品索引,如图一所示
<table>
<tr>
<th>Name</th>
<th>Size</th>
<th>Price</th>
<th>Category</th>
<th>Image</th>
</tr>
<% Product.all.each do |f| %>
<tr>
<td><%= link_to f.name, product_path(@products) %></td>
<td><%= f.size %></td>
<td><%= f.price %></td>
<td><%= image_tag(f.image, :width => "60%") %></td>
<% end %>
</tr>
</tr>
</table>
我遇到的另一个问题是当我访问products/1/edit 时
并填写表格,它给出了另一个问题,说No route matches [PUT] "/products/1/edit"在我的路线中我已经将它作为resources :products
这是 products/edit.html.erb
<% provide(:title, "Edit Product - ") %>
<h1>Edit Product <%= @products %></h1>
<p class="lead">Fill out the following fields</p>
<%= render 'products/form', products: @products, url: products_path(@products), method: :put %>
这是products/_form.html.erb
<div class="form">
<%= form_for :products, method: method do |f| %>
<%= render 'shared/flash_messages' %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: 'Product Name' %>
</div>
<div class="form-group">
<%= f.label :size %>
<%= f.text_field :size, class: 'form-control', placeholder: 'Product Size' %>
</div>
<div class="form-group">
<%= f.label :price %>
<%= f.text_field :price, class: 'form-control', placeholder: 'Product Size' %>
</div>
<div class="form-group">
<%= f.label :image %>
<%= f.file_field :image, hidden: true %>
</div>
</div>
<%= f.submit class: 'btn btn-primary btn-primary--wide', value: 'Update Product' %>
<% end %>
</div>
谢谢你!
【问题讨论】:
标签: html ruby-on-rails ruby